"""
主窗口模块 - 应用程序的主窗口类
"""

import os
import json
from PySide2.QtWidgets import (QMainWindow, QWidget, QHBoxLayout, QVBoxLayout,
                              QStackedWidget, QMessageBox, QFileDialog, QLabel,
                              QLineEdit, QPushButton, QProgressBar, QTextEdit,
                              QFrame, QGroupBox, QSpinBox, QPlainTextEdit, QScrollArea,
                              QDialog, QDialogButtonBox)
from PySide2.QtCore import Qt, QTimer, QUrl
from PySide2.QtGui import QFont, QIcon, QPixmap, QTextDocument, QPainter, QPainterPath, QColor, QPen, QRegion, QBitmap

from ui_styles import UIStyles
from ui_components import SidebarComponent, DownloadPageComponent
from downloader_core import DownloaderCore
from download_thread import DownloadThread
from config import APP_CONFIG
from vmq_page import WeimiquanPage
from cookie_manager import CookieManager
from security_manager import get_password, store_password
from neon_particle_effect import NeonParticleEffect
from custom_titlebar import CustomTitleBar

# 导入快手批量下载相关模块
import requests
import json
import time
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from PySide2.QtCore import QThread, Signal


class KuaishouBatchDownloadThread(QThread):
    """快手批量下载线程 - 集成快手批量下载逻辑"""
    update_log = Signal(str)
    update_progress = Signal(int)
    finished = Signal()
    error = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.user_id = ""
        self.save_path = ""
        self.stop_requested = False
        self.session = None
        self.author_name = None
        self.download_path = None
        self.payload = None

    def set_params(self, user_id, save_path):
        """设置下载参数"""
        self.user_id = user_id
        self.save_path = save_path

    def request_stop(self):
        """请求停止下载"""
        self.stop_requested = True

    def _setup_session(self):
        """设置session的请求头和Cookie"""
        self.session = requests.Session()

        # 设置User-Agent
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
            "Content-Type": "application/json",
            "Referer": f"https://kuaishou.cn/profile/{self.user_id}",
        })

        # 设置Cookie
        cookies = {
            "kpf": "PC_WEB",
            "clientid": "3",
            "did": "web_cabb2ac62d58ddcb1c807794a5c5a043",
            "userId": "254593641",
            "kuaishou.server.webday7_st": "ChprdWFpc2hvdS5zZXJ2ZXIud2ViZGF5Ny5zdBKwAVDJGlAKJdL3MIuIoUaDM_S6oJt0_t8Dk28-KS7mXHIFzXxoQHsjLp7jpxTXOQi59PcTVqfGUlAM7OeW6ySUz4rl_Yuz4UL_40Q7JipCmNTkSuwKr6p20DA068NpRuTd4FCzej3Ml12SRnZJmRh7Soht0nunm4MljYjrkX7faKtbsIB5U5pFigvcpQl6tofD_Osl0qOBDTs2Xw3aWgmjaSXlfhiucu36RhLrf4euxIHgGhJglXWxx8RvW8kJJMTzKPTd1I8iICtsKJvZFJMy3I45clWXTOkh_p6fcNVOw5QBBNpRDWipKAUwAQ",
            "kuaishou.server.webday7_ph": "54fef7242fe0dd4bde4aac451c27c7ced4b7",
            "kpn": "KUAISHOU_VISION",
        }
        self.session.cookies.update(cookies)

        # 设置GraphQL查询载荷
        self.payload = {
            "operationName": "visionProfilePhotoList",
            "variables": {"userId": self.user_id, "pcursor": "", "page": "profile"},
            "query": """
                fragment photoContent on PhotoEntity {
                    __typename
                    id
                    duration
                    caption
                    originCaption
                    likeCount
                    viewCount
                    commentCount
                    realLikeCount
                    coverUrl
                    photoUrl
                    photoH265Url
                    manifest
                    manifestH265
                    videoResource
                    coverUrls {
                        url
                        __typename
                    }
                    timestamp
                    expTag
                    animatedCoverUrl
                    distance
                    videoRatio
                    liked
                    stereoType
                    profileUserTopPhoto
                    musicBlocked
                    riskTagContent
                    riskTagUrl
                }
                fragment recoPhotoFragment on recoPhotoEntity {
                    __typename
                    id
                    duration
                    caption
                    originCaption
                    likeCount
                    viewCount
                    commentCount
                    realLikeCount
                    coverUrl
                    photoUrl
                    photoH265Url
                    manifest
                    manifestH265
                    videoResource
                    coverUrls {
                        url
                        __typename
                    }
                    timestamp
                    expTag
                    animatedCoverUrl
                    distance
                    videoRatio
                    liked
                    stereoType
                    profileUserTopPhoto
                    musicBlocked
                    riskTagContent
                    riskTagUrl
                }
                fragment feedContentWithLiveInfo on Feed {
                    type
                    author {
                        id
                        name
                        headerUrl
                        following
                        livingInfo
                        headerUrls {
                            url
                            __typename
                        }
                        __typename
                    }
                    photo {
                        ...photoContent
                        ...recoPhotoFragment
                        __typename
                    }
                    canAddComment
                    llsid
                    status
                    currentPcursor
                    tags {
                        type
                        name
                        __typename
                    }
                    __typename
                }
                query visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {
                    visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {
                        result
                        llsid
                        webPageArea
                        feeds {
                            ...feedContentWithLiveInfo
                            __typename
                        }
                        hostName
                        pcursor
                        __typename
                    }
                }
            """,
        }

    def _sanitize_filename(self, filename):
        """清理文件名，移除非法字符"""
        if not filename:
            return ""

        # 移除换行符和制表符
        filename = filename.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')

        # 移除或替换Windows非法字符
        illegal_chars = r'[<>:"/\\|?*]'
        filename = re.sub(illegal_chars, "_", filename)

        # 移除控制字符
        filename = re.sub(r'[\x00-\x1f\x7f-\x9f]', "", filename)

        # 替换多个连续空格为单个空格
        filename = re.sub(r'\s+', ' ', filename)

        # 移除开头和结尾的空格和点号
        filename = filename.strip(' .')

        # 限制长度（Windows路径限制）
        if len(filename) > 100:
            filename = filename[:100].strip(' .')

        # 如果清理后为空，返回默认名称
        if not filename:
            filename = "untitled"

        return filename

    def get_video_list(self):
        """获取用户的所有视频列表"""
        videos = []
        pcursor = ""
        page_count = 0

        self.update_log.emit(f"开始获取用户 {self.user_id} 的视频列表...")

        try:
            while pcursor != "no_more":
                if self.stop_requested:
                    self.update_log.emit("用户中断获取视频列表")
                    break

                try:
                    # 复制载荷并设置游标
                    current_payload = self.payload.copy()
                    current_payload["variables"]["pcursor"] = pcursor

                    # 发送请求
                    response = self.session.post("https://kuaishou.cn/graphql", json=current_payload)
                    response.raise_for_status()
                    data = response.json()

                    # 解析响应数据
                    vision_data = data.get("data", {}).get("visionProfilePhotoList", {})
                    feeds = vision_data.get("feeds", [])

                    # 提取作者信息（第一次获取时）
                    if self.author_name is None and feeds:
                        first_feed = feeds[0]
                        author = first_feed.get("author", {})
                        if author:
                            self.author_name = author.get("name", f"user_{self.user_id}")
                            # 清理作者名，用作文件夹名
                            safe_author_name = self._sanitize_filename(self.author_name)
                            self.download_path = os.path.join(self.save_path, safe_author_name)
                            # 创建作者文件夹
                            os.makedirs(self.download_path, exist_ok=True)
                            self.update_log.emit(f"作者: {self.author_name}")
                            self.update_log.emit(f"下载路径: {self.download_path}")

                    # 提取视频信息
                    for feed in feeds:
                        photo = feed.get("photo", {})
                        if photo:
                            video_info = {
                                "id": photo.get("id", ""),
                                "url": photo.get("photoUrl", ""),
                                "caption": photo.get("caption", ""),
                                "duration": photo.get("duration", 0),
                                "likeCount": photo.get("likeCount", 0),
                                "viewCount": photo.get("viewCount", 0),
                                "timestamp": photo.get("timestamp", 0),
                            }
                            if video_info["id"] and video_info["url"]:
                                videos.append(video_info)

                    # 获取下一页游标
                    pcursor = vision_data.get("pcursor", "no_more")
                    page_count += 1

                    self.update_log.emit(f"第 {page_count} 页: 获取到 {len(feeds)} 个视频，总计 {len(videos)} 个")

                    # 避免请求过快
                    time.sleep(0.5)

                except Exception as e:
                    self.update_log.emit(f"获取视频列表时出错: {e}")
                    break

        except Exception as e:
            self.update_log.emit(f"获取视频列表异常: {e}")

        self.update_log.emit(f"视频列表获取完成，共找到 {len(videos)} 个视频")
        return videos

    def download_video(self, video_info):
        """下载单个视频"""
        video_id = video_info["id"]
        video_url = video_info["url"]
        caption = video_info.get("caption", "")

        try:
            # 构造文件名
            safe_caption = self._sanitize_filename(caption)
            if safe_caption and safe_caption != "untitled":
                filename = f"{video_id}_{safe_caption}.mp4"
            else:
                filename = f"{video_id}.mp4"

            # 再次验证文件名长度，确保完整路径不会太长
            max_filename_length = 200  # 保守估计
            if len(filename) > max_filename_length:
                # 截断标题部分，保留视频ID
                max_caption_length = max_filename_length - len(video_id) - 10  # 10是"_"和".mp4"的长度
                if max_caption_length > 0:
                    safe_caption = safe_caption[:max_caption_length].strip(' .')
                    filename = f"{video_id}_{safe_caption}.mp4"
                else:
                    filename = f"{video_id}.mp4"

            filepath = os.path.join(self.download_path, filename)

            # 验证完整路径长度（Windows限制260字符）
            if len(filepath) > 250:
                # 使用更短的文件名
                filename = f"{video_id}.mp4"
                filepath = os.path.join(self.download_path, filename)

            # 检查文件是否已存在
            if os.path.exists(filepath):
                self.update_log.emit(f"⚠ 文件已存在，跳过: {filename}")
                return True

            # 下载视频
            self.update_log.emit(f"📥 开始下载: {filename}")
            response = self.session.get(video_url, stream=True, timeout=30)
            response.raise_for_status()

            # 获取文件大小
            total_size = int(response.headers.get("content-length", 0))
            downloaded_size = 0

            # 创建临时文件，下载完成后重命名
            temp_filepath = filepath + ".tmp"

            with open(temp_filepath, "wb") as f:
                for chunk in response.iter_content(chunk_size=8192):
                    if self.stop_requested:
                        # 如果用户请求停止，删除临时文件并返回
                        f.close()
                        if os.path.exists(temp_filepath):
                            os.remove(temp_filepath)
                        return False

                    if chunk:
                        f.write(chunk)
                        downloaded_size += len(chunk)

            # 验证下载完整性
            if total_size > 0 and downloaded_size != total_size:
                self.update_log.emit(f"⚠ 下载不完整: {filename} ({downloaded_size}/{total_size} bytes)")
                if os.path.exists(temp_filepath):
                    os.remove(temp_filepath)
                return False

            # 重命名临时文件为最终文件
            if os.path.exists(temp_filepath):
                os.rename(temp_filepath, filepath)

            self.update_log.emit(f"✅ 下载完成: {filename} ({downloaded_size} bytes)")
            return True

        except Exception as e:
            self.update_log.emit(f"❌ 下载失败 {video_id}: {e}")
            # 清理可能的不完整文件
            try:
                if "filepath" in locals() and os.path.exists(filepath):
                    os.remove(filepath)
                if "temp_filepath" in locals() and os.path.exists(temp_filepath):
                    os.remove(temp_filepath)
            except:
                pass
            return False

    def run(self):
        """运行批量下载"""
        try:
            self.update_log.emit("=" * 50)
            self.update_log.emit(f"快手视频批量下载器")
            self.update_log.emit(f"用户ID: {self.user_id}")
            self.update_log.emit(f"保存路径: {self.save_path}")
            self.update_log.emit("=" * 50)

            # 创建基础下载目录
            os.makedirs(self.save_path, exist_ok=True)

            # 初始化session
            self._setup_session()

            # 获取视频列表
            videos = self.get_video_list()

            if self.stop_requested:
                self.update_log.emit("用户取消下载")
                return

            if not videos:
                self.error.emit("未找到任何视频，请检查用户ID是否正确")
                return

            if not self.download_path:
                self.error.emit("未能获取作者信息，无法创建下载目录")
                return

            self.update_log.emit(f"\n开始下载 {len(videos)} 个视频...")

            # 并发下载
            success_count = 0
            failed_count = 0

            with ThreadPoolExecutor(max_workers=5) as executor:
                # 提交所有下载任务
                future_to_video = {
                    executor.submit(self.download_video, video): video for video in videos
                }

                # 处理完成的任务
                try:
                    for i, future in enumerate(as_completed(future_to_video)):
                        if self.stop_requested:
                            self.update_log.emit("用户中断下载，正在停止...")
                            # 取消未完成的任务
                            for f in future_to_video:
                                f.cancel()
                            break

                        video = future_to_video[future]
                        try:
                            if future.result():
                                success_count += 1
                            else:
                                failed_count += 1
                        except Exception as e:
                            self.update_log.emit(f"❌ 任务执行异常 {video['id']}: {e}")
                            failed_count += 1

                        # 更新进度
                        progress = int((i + 1) / len(videos) * 100)
                        self.update_progress.emit(progress)

                except Exception as e:
                    self.update_log.emit(f"下载过程中出现异常: {e}")

            # 输出统计信息
            self.update_log.emit("\n" + "=" * 50)
            self.update_log.emit(f"下载完成！")
            self.update_log.emit(f"成功: {success_count}")
            self.update_log.emit(f"失败: {failed_count}")
            self.update_log.emit(f"总计: {len(videos)}")
            if len(videos) > 0:
                self.update_log.emit(f"成功率: {success_count/len(videos)*100:.1f}%")
            self.update_log.emit("=" * 50)

            self.finished.emit()

        except Exception as e:
            self.error.emit(str(e))
            import traceback
            traceback.print_exc()


class DouyinVideoPage(DownloadPageComponent):
    """抖音视频下载页面 - 完全按照原版设计"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.download_thread = None
        self.is_downloading = False
        self.setup_ui()

    def setup_ui(self):
        """设置UI - 完全按照原版"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """)

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet("""
            QWidget {
                background: transparent;
            }
        """)

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # 标题区域 - 完全按照原版
        title_frame = QFrame()
        title_frame.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.08);
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
        """)
        title_frame.setFixedHeight(60)
        title_layout = QHBoxLayout(title_frame)
        title_layout.setContentsMargins(15, 5, 15, 5)

        # 左侧装饰
        left_decor = QFrame()
        left_decor.setFixedWidth(4)
        left_decor.setStyleSheet("background-color: #6ca6fd; border-radius: 2px;")

        # 创建切换按钮组（替代原来的标题）
        self.button_group_widget = QWidget()
        button_group_layout = QHBoxLayout(self.button_group_widget)
        button_group_layout.setContentsMargins(0, 0, 0, 0)
        button_group_layout.setSpacing(0)  # 按钮之间无间距

        # 抖音视频下载按钮（当前激活状态）
        self.video_download_btn = QPushButton("抖音视频下载")
        self.video_download_btn.setMinimumHeight(40)
        self.video_download_btn.clicked.connect(self.switch_to_video_download)

        # 抖音图片下载按钮
        self.image_download_btn = QPushButton("抖音图片下载")
        self.image_download_btn.setMinimumHeight(40)
        self.image_download_btn.clicked.connect(self.switch_to_image_download)

        # 添加按钮到按钮组
        button_group_layout.addWidget(self.video_download_btn)
        button_group_layout.addWidget(self.image_download_btn)

        # 设置初始状态（视频下载激活）
        self.update_button_styles(True)

        title_layout.addWidget(left_decor)
        title_layout.addWidget(self.button_group_widget)
        title_layout.addStretch()

        layout.addWidget(title_frame)

        # URL输入区域 - 完全按照原版
        url_group = QGroupBox("视频链接")
        url_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        url_layout = QHBoxLayout(url_group)
        url_layout.setContentsMargins(12, 15, 12, 12)

        url_label = QLabel("链接:")
        url_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入抖音视频链接 (例如: https://www.douyin.com/jingxuan?modal_id=7525489888829934894)")
        self.url_input.setMinimumHeight(42)
        self.url_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        url_layout.addWidget(url_label)
        url_layout.addWidget(self.url_input, 1)

        layout.addWidget(url_group)

        # 保存路径区域 - 完全按照原版
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("路径:")
        path_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.path_input = QLineEdit()
        self.path_input.setText(APP_CONFIG['download_paths']['douyin_video'])
        self.path_input.setMinimumHeight(42)
        self.path_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        from ui_styles import UIStyles
        self.ui_styles = UIStyles()

        self.browse_btn = QPushButton("浏览")
        self.browse_btn.setMinimumHeight(42)
        self.browse_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.browse_btn.clicked.connect(self.browse_path)

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_input, 1)
        path_layout.addWidget(self.browse_btn)

        layout.addWidget(path_group)

        # 操作按钮区域 - 按照第二个页面样式
        button_group = QGroupBox("操作")
        button_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        self.download_btn = QPushButton("开始下载")
        self.download_btn.setMinimumHeight(42)
        self.download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
        self.download_btn.clicked.connect(self.start_download)

        self.clear_btn = QPushButton("清空日志")
        self.clear_btn.setMinimumHeight(42)
        self.clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.clear_btn.clicked.connect(self.clear_log)

        button_layout.addWidget(self.download_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()

        layout.addWidget(button_group)

        # 下载进度区域 - 完全按照快手页面样式
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimumHeight(30)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """)

        progress_layout.addWidget(self.progress_bar)

        layout.addWidget(progress_group)

        # 下载日志区域 - 完全按照原版
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.log_text = QTextEdit()
        self.log_text.setMinimumHeight(540)  # 增高三倍 (180 * 3)
        self.log_text.setReadOnly(True)
        self.log_text.setStyleSheet("""
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                padding: 12px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                line-height: 1.4;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
        """)

        log_layout.addWidget(self.log_text)
        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)
        
    def browse_path(self):
        """浏览保存路径"""
        path = QFileDialog.getExistingDirectory(self, "选择保存路径")
        if path:
            self.path_input.setText(path)
    
    def start_download(self):
        """开始/停止下载"""
        if self.is_downloading:
            # 停止下载
            self.stop_download()
        else:
            # 开始下载
            self.begin_download()

    def begin_download(self):
        """开始下载"""
        try:
            url = self.url_input.text().strip()
            save_path = self.path_input.text().strip()

            if not url:
                show_custom_message(self, "警告", "请输入视频链接!", "warning")
                return

            if not save_path:
                show_custom_message(self, "警告", "请选择保存路径!", "warning")
                return

            if not os.path.exists(save_path):
                os.makedirs(save_path, exist_ok=True)

            # 检查是否已经在下载
            if hasattr(self, 'download_thread') and self.download_thread and self.download_thread.isRunning():
                self.append_log("已有下载任务在进行中，请等待完成或停止当前任务")
                return

            # 开始下载
            self.is_downloading = True
            self.download_btn.setText("停止下载")
            self.progress_bar.setValue(0)

            # 创建下载线程
            self.download_thread = DownloadThread(self)  # 设置父对象
            self.download_thread.update_log.connect(self.append_log)
            self.download_thread.update_progress.connect(self.update_progress)
            self.download_thread.finished.connect(self.download_finished)
            self.download_thread.error.connect(self.download_error)

            # 设置下载参数 - 使用主窗口的下载器实例
            main_window = self.get_main_window()
            if main_window and hasattr(main_window, 'downloader_core'):
                downloader = main_window.downloader_core
            else:
                downloader = DownloaderCore()

            self.download_thread.set_params(
                downloader.get_video_url_and_download,
                (url, save_path, self.download_thread.update_progress.emit, self.download_thread.update_log.emit)
            )

            self.download_thread.start()
            self.append_log("开始下载抖音视频...")

        except Exception as e:
            self.append_log(f"启动下载失败: {str(e)}")
            self.is_downloading = False
            self.download_btn.setText("开始下载")
            import traceback
            traceback.print_exc()

    def stop_download(self):
        """停止下载"""
        try:
            if hasattr(self, 'download_thread') and self.download_thread and self.download_thread.isRunning():
                self.append_log("正在停止下载...")
                # 先尝试优雅停止
                self.download_thread.request_stop()
                if not self.download_thread.wait(3000):  # 等待3秒
                    # 如果优雅停止失败，强制终止
                    self.append_log("强制终止下载线程...")
                    self.download_thread.terminate()
                    self.download_thread.wait()

            self.is_downloading = False
            self.download_btn.setText("开始下载")
            self.append_log("下载已停止")
        except Exception as e:
            self.append_log(f"停止下载时出错: {str(e)}")
            self.is_downloading = False
            self.download_btn.setText("开始下载")
    
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(int(value))
    
    def append_log(self, message):
        """添加日志"""
        self.log_text.append(f"[{self.get_current_time()}] {message}")
        self.log_text.ensureCursorVisible()
    
    def clear_log(self):
        """清空日志"""
        self.log_text.clear()
    
    def download_finished(self):
        """下载完成"""
        try:
            self.is_downloading = False
            self.download_btn.setText("开始下载")
            self.progress_bar.setValue(100)
            self.append_log("✅ 下载完成!")

            # 清理线程引用
            if hasattr(self, 'download_thread'):
                self.download_thread = None
        except Exception as e:
            self.append_log(f"下载完成处理出错: {str(e)}")

    def download_error(self, error_msg):
        """下载错误"""
        try:
            self.is_downloading = False
            self.download_btn.setText("开始下载")
            self.append_log(f"❌ 下载失败: {error_msg}")

            # 清理线程引用
            if hasattr(self, 'download_thread'):
                self.download_thread = None

            # 显示错误对话框，但要防止过长的错误信息
            short_error = error_msg.split('\n')[0] if '\n' in error_msg else error_msg
            if len(short_error) > 200:
                short_error = short_error[:200] + "..."
            show_custom_message(self, "下载错误", f"下载失败:\n{short_error}", "error")
        except Exception as e:
            self.append_log(f"错误处理出错: {str(e)}")
    
    def get_current_time(self):
        """获取当前时间"""
        from datetime import datetime
        return datetime.now().strftime("%H:%M:%S")

    def get_main_window(self):
        """获取主窗口实例"""
        widget = self
        while widget:
            if isinstance(widget, MainWindow):
                return widget
            widget = widget.parent()
        return None

    def update_button_styles(self, video_active):
        """更新按钮样式"""
        if video_active:
            # 视频下载按钮激活样式（使用primary样式）
            self.video_download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
            # 图片下载按钮非激活样式（使用default样式）
            self.image_download_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        else:
            # 图片下载按钮激活样式（使用primary样式）
            self.image_download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
            # 视频下载按钮非激活样式（使用default样式）
            self.video_download_btn.setStyleSheet(self.ui_styles.get_button_style("default"))

    def switch_to_video_download(self):
        """切换到抖音视频下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 切换到视频下载页面（当前页面，索引0）
            main_window.stacked_widget.setCurrentIndex(0)

    def switch_to_image_download(self):
        """切换到抖音图片下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 直接切换到抖音图片下载页面（索引1），不经过菜单映射
            main_window.stacked_widget.setCurrentIndex(1)


class DouyinImagePage(DownloadPageComponent):
    """抖音图片下载页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.download_thread = None
        self.is_downloading = False
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI - 完全按照原版"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """)

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet("""
            QWidget {
                background: transparent;
            }
        """)

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # 标题区域 - 完全按照原版
        title_frame = QFrame()
        title_frame.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.08);
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
        """)
        title_frame.setFixedHeight(60)
        title_layout = QHBoxLayout(title_frame)
        title_layout.setContentsMargins(15, 5, 15, 5)

        # 左侧装饰
        left_decor = QFrame()
        left_decor.setFixedWidth(4)
        left_decor.setStyleSheet("background-color: #6ca6fd; border-radius: 2px;")

        # 创建切换按钮组（替代原来的标题）
        self.button_group_widget = QWidget()
        button_group_layout = QHBoxLayout(self.button_group_widget)
        button_group_layout.setContentsMargins(0, 0, 0, 0)
        button_group_layout.setSpacing(0)  # 按钮之间无间距

        # 抖音视频下载按钮
        self.video_download_btn = QPushButton("抖音视频下载")
        self.video_download_btn.setMinimumHeight(40)
        self.video_download_btn.clicked.connect(self.switch_to_video_download)

        # 抖音图片下载按钮（当前激活状态）
        self.image_download_btn = QPushButton("抖音图片下载")
        self.image_download_btn.setMinimumHeight(40)
        self.image_download_btn.clicked.connect(self.switch_to_image_download)

        # 添加按钮到按钮组
        button_group_layout.addWidget(self.video_download_btn)
        button_group_layout.addWidget(self.image_download_btn)

        # 设置初始状态（图片下载激活）
        self.update_button_styles(False)

        title_layout.addWidget(left_decor)
        title_layout.addWidget(self.button_group_widget)
        title_layout.addStretch()

        layout.addWidget(title_frame)

        # URL输入区域 - 完全按照原版
        url_group = QGroupBox("图片链接")
        url_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        url_layout = QHBoxLayout(url_group)
        url_layout.setContentsMargins(12, 15, 12, 12)

        url_label = QLabel("链接:")
        url_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入抖音图片帖子链接")
        self.url_input.setMinimumHeight(42)
        self.url_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        url_layout.addWidget(url_label)
        url_layout.addWidget(self.url_input, 1)

        layout.addWidget(url_group)

        # 保存路径区域 - 完全按照原版
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("路径:")
        path_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.path_input = QLineEdit()
        self.path_input.setPlaceholderText("选择图片保存位置...")
        self.path_input.setText(APP_CONFIG['download_paths']['douyin_image'])
        self.path_input.setMinimumHeight(42)
        self.path_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        self.browse_btn = QPushButton("浏览")
        self.browse_btn.setMinimumHeight(42)
        self.browse_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.browse_btn.clicked.connect(self.browse_path)

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_input, 1)
        path_layout.addWidget(self.browse_btn)

        layout.addWidget(path_group)

        # 操作按钮区域 - 完全按照原版
        button_group = QGroupBox("操作")
        button_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        self.download_btn = QPushButton("开始下载")
        self.download_btn.setMinimumHeight(42)
        self.download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
        self.download_btn.clicked.connect(self.start_download)

        self.clear_btn = QPushButton("清空日志")
        self.clear_btn.setMinimumHeight(42)
        self.clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.clear_btn.clicked.connect(self.clear_log)

        button_layout.addWidget(self.download_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()

        layout.addWidget(button_group)

        # 下载进度区域 - 完全按照原版
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimumHeight(30)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """)

        progress_layout.addWidget(self.progress_bar)

        layout.addWidget(progress_group)

        # 下载日志区域 - 完全按照原版
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.log_text = QTextEdit()
        self.log_text.setMinimumHeight(540)  # 增高三倍 (180 * 3)
        self.log_text.setReadOnly(True)
        self.log_text.setStyleSheet("""
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                padding: 12px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                line-height: 1.4;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
        """)

        log_layout.addWidget(self.log_text, 1)

        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)
        
    def browse_path(self):
        """浏览保存路径"""
        path = QFileDialog.getExistingDirectory(self, "选择保存路径")
        if path:
            self.path_input.setText(path)
    
    def start_download(self):
        """开始/停止下载"""
        if self.is_downloading:
            # 停止下载
            self.stop_download()
        else:
            # 开始下载
            self.begin_download()

    def begin_download(self):
        """开始下载"""
        url = self.url_input.text().strip()
        save_path = self.path_input.text().strip()

        if not url:
            show_custom_message(self, "警告", "请输入图片链接!", "warning")
            return

        if not save_path:
            show_custom_message(self, "警告", "请选择保存路径!", "warning")
            return

        if not os.path.exists(save_path):
            os.makedirs(save_path, exist_ok=True)

        # 开始下载
        self.is_downloading = True
        self.download_btn.setText("停止下载")
        self.progress_bar.setValue(0)

        # 创建下载线程
        self.download_thread = DownloadThread()
        self.download_thread.update_log.connect(self.append_log)
        self.download_thread.update_progress.connect(self.update_progress)
        self.download_thread.finished.connect(self.download_finished)
        self.download_thread.error.connect(self.download_error)

        # 设置下载参数 - 使用主窗口的下载器实例
        main_window = self.get_main_window()
        if main_window and hasattr(main_window, 'downloader_core'):
            downloader = main_window.downloader_core
        else:
            downloader = DownloaderCore()

        self.download_thread.set_params(
            downloader.get_douyin_img,
            (url, save_path, self.download_thread.update_progress.emit, self.download_thread.update_log.emit)
        )

        self.download_thread.start()
        self.append_log("开始下载抖音图片...")

    def stop_download(self):
        """停止下载"""
        if self.download_thread and self.download_thread.isRunning():
            # 先尝试优雅停止
            self.download_thread.request_stop()
            if not self.download_thread.wait(3000):  # 等待3秒
                # 如果优雅停止失败，强制终止
                self.download_thread.terminate()
                self.download_thread.wait()

        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.append_log("下载已停止")
    
    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(int(value))
    
    def append_log(self, message):
        """添加日志"""
        self.log_text.append(f"[{self.get_current_time()}] {message}")
        self.log_text.ensureCursorVisible()
    
    def clear_log(self):
        """清空日志"""
        self.log_text.clear()
    
    def download_finished(self):
        """下载完成"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.progress_bar.setValue(100)
        self.append_log("下载完成!")

    def download_error(self, error_msg):
        """下载错误"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.append_log(f"下载失败: {error_msg}")
        show_custom_message(self, "错误", f"下载失败: {error_msg}", "error")
    
    def get_current_time(self):
        """获取当前时间"""
        from datetime import datetime
        return datetime.now().strftime("%H:%M:%S")

    def update_button_styles(self, video_active):
        """更新按钮样式"""
        if video_active:
            # 视频下载按钮激活样式（使用primary样式）
            self.video_download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
            # 图片下载按钮非激活样式（使用default样式）
            self.image_download_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        else:
            # 图片下载按钮激活样式（使用primary样式）
            self.image_download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
            # 视频下载按钮非激活样式（使用default样式）
            self.video_download_btn.setStyleSheet(self.ui_styles.get_button_style("default"))

    def switch_to_video_download(self):
        """切换到抖音视频下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 切换到视频下载页面（索引0）
            main_window.stacked_widget.setCurrentIndex(0)

    def switch_to_image_download(self):
        """切换到抖音图片下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 保持在当前页面（索引1）
            main_window.stacked_widget.setCurrentIndex(1)

    def get_main_window(self):
        """获取主窗口实例"""
        widget = self
        while widget:
            if isinstance(widget, MainWindow):
                return widget
            widget = widget.parent()
        return None


class KuaishouVideoPage(DownloadPageComponent):
    """快手视频下载页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.download_thread = None
        self.is_downloading = False
        self.setup_ui()

    def setup_ui(self):
        """设置UI - 完全按照原版"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """)

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet("""
            QWidget {
                background: transparent;
            }
        """)

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # 标题区域 - 完全按照原版
        title_frame = QFrame()
        title_frame.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.08);
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
        """)
        title_frame.setFixedHeight(60)
        title_layout = QHBoxLayout(title_frame)
        title_layout.setContentsMargins(15, 5, 15, 5)

        # 左侧装饰
        left_decor = QFrame()
        left_decor.setFixedWidth(4)
        left_decor.setStyleSheet("background-color: #6ca6fd; border-radius: 2px;")

        # 创建切换按钮组（替代原来的标题）
        self.button_group_widget = QWidget()
        button_group_layout = QHBoxLayout(self.button_group_widget)
        button_group_layout.setContentsMargins(0, 0, 0, 0)
        button_group_layout.setSpacing(0)  # 按钮之间无间距

        # 快手视频下载按钮（当前激活状态）
        self.video_download_btn = QPushButton("快手视频下载")
        self.video_download_btn.setMinimumHeight(40)
        self.video_download_btn.clicked.connect(self.switch_to_video_download)

        # 快手批量下载按钮
        self.batch_download_btn = QPushButton("快手批量下载")
        self.batch_download_btn.setMinimumHeight(40)
        self.batch_download_btn.clicked.connect(self.switch_to_batch_download)

        # 添加按钮到按钮组
        button_group_layout.addWidget(self.video_download_btn)
        button_group_layout.addWidget(self.batch_download_btn)

        # 设置初始状态（视频下载激活）
        self.update_button_styles(True)

        title_layout.addWidget(left_decor)
        title_layout.addWidget(self.button_group_widget)
        title_layout.addStretch()

        layout.addWidget(title_frame)

        # URL输入区域 - 完全按照原版
        url_group = QGroupBox("视频链接")
        url_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        url_layout = QHBoxLayout(url_group)
        url_layout.setContentsMargins(12, 15, 12, 12)

        url_label = QLabel("链接:")
        url_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入快手视频链接 (例如: https://www.kuaishou.com/short-video/3xq9d8xp...)")
        self.url_input.setMinimumHeight(42)
        self.url_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        url_layout.addWidget(url_label)
        url_layout.addWidget(self.url_input, 1)

        layout.addWidget(url_group)

        # 保存路径区域 - 完全按照原版
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("路径:")
        path_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.path_input = QLineEdit()
        self.path_input.setPlaceholderText("选择视频保存位置...")
        self.path_input.setText(APP_CONFIG['download_paths']['kuaishou_video'])
        self.path_input.setMinimumHeight(42)
        self.path_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        from ui_styles import UIStyles
        self.ui_styles = UIStyles()

        self.browse_btn = QPushButton("浏览")
        self.browse_btn.setMinimumHeight(42)
        self.browse_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.browse_btn.clicked.connect(self.browse_path)

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_input, 1)
        path_layout.addWidget(self.browse_btn)

        layout.addWidget(path_group)

        # 操作按钮区域 - 完全按照原版
        button_group = QGroupBox("操作")
        button_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        self.download_btn = QPushButton("开始下载")
        self.download_btn.setMinimumHeight(42)
        self.download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
        self.download_btn.clicked.connect(self.start_download)

        self.clear_btn = QPushButton("清空日志")
        self.clear_btn.setMinimumHeight(42)
        self.clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.clear_btn.clicked.connect(self.clear_log)

        button_layout.addWidget(self.download_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()

        layout.addWidget(button_group)

        # 下载进度区域 - 完全按照原版
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimumHeight(30)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """)

        progress_layout.addWidget(self.progress_bar)

        layout.addWidget(progress_group)

        # 下载日志区域 - 完全按照原版
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.log_text = QTextEdit()
        self.log_text.setMinimumHeight(540)  # 增高三倍 (180 * 3)
        self.log_text.setReadOnly(True)
        self.log_text.setStyleSheet("""
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                padding: 12px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                line-height: 1.4;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
        """)

        log_layout.addWidget(self.log_text, 1)

        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)

    def browse_path(self):
        """浏览保存路径"""
        path = QFileDialog.getExistingDirectory(self, "选择保存路径")
        if path:
            self.path_input.setText(path)

    def start_download(self):
        """开始/停止下载"""
        if self.is_downloading:
            # 停止下载
            self.stop_download()
        else:
            # 开始下载
            self.begin_download()

    def begin_download(self):
        """开始下载"""
        url = self.url_input.text().strip()
        save_path = self.path_input.text().strip()

        if not url:
            show_custom_message(self, "警告", "请输入视频链接!", "warning")
            return

        if not save_path:
            show_custom_message(self, "警告", "请选择保存路径!", "warning")
            return

        if not os.path.exists(save_path):
            os.makedirs(save_path, exist_ok=True)

        # 开始下载
        self.is_downloading = True
        self.download_btn.setText("停止下载")
        self.progress_bar.setValue(0)

        # 创建下载线程
        self.download_thread = DownloadThread()
        self.download_thread.update_log.connect(self.append_log)
        self.download_thread.update_progress.connect(self.update_progress)
        self.download_thread.finished.connect(self.download_finished)
        self.download_thread.error.connect(self.download_error)

        # 设置下载参数 - 使用主窗口的下载器实例
        main_window = self.get_main_window()
        if main_window and hasattr(main_window, 'downloader_core'):
            downloader = main_window.downloader_core
        else:
            downloader = DownloaderCore()

        self.download_thread.set_params(
            downloader.download_kuaishou_video,
            (url, save_path, self.download_thread.update_progress.emit, self.download_thread.update_log.emit)
        )

        self.download_thread.start()
        self.append_log("开始下载快手视频...")

    def stop_download(self):
        """停止下载"""
        if self.download_thread and self.download_thread.isRunning():
            # 先尝试优雅停止
            self.download_thread.request_stop()
            if not self.download_thread.wait(3000):  # 等待3秒
                # 如果优雅停止失败，强制终止
                self.download_thread.terminate()
                self.download_thread.wait()

        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.append_log("下载已停止")

    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(int(value))

    def append_log(self, message):
        """添加日志"""
        self.log_text.append(f"[{self.get_current_time()}] {message}")
        self.log_text.ensureCursorVisible()

    def clear_log(self):
        """清空日志"""
        self.log_text.clear()

    def download_finished(self):
        """下载完成"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.progress_bar.setValue(100)
        self.append_log("下载完成!")

    def download_error(self, error_msg):
        """下载错误"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.append_log(f"下载失败: {error_msg}")
        show_custom_message(self, "错误", f"下载失败: {error_msg}", "error")

    def get_current_time(self):
        """获取当前时间"""
        from datetime import datetime
        return datetime.now().strftime("%H:%M:%S")

    def get_main_window(self):
        """获取主窗口实例"""
        widget = self
        while widget:
            if isinstance(widget, MainWindow):
                return widget
            widget = widget.parent()
        return None

    def update_button_styles(self, video_active):
        """更新按钮样式"""
        from ui_styles import UIStyles
        ui_styles = UIStyles()

        if video_active:
            # 视频下载按钮激活样式（使用primary样式）
            self.video_download_btn.setStyleSheet(ui_styles.get_button_style("primary"))
            # 批量下载按钮非激活样式（使用default样式）
            self.batch_download_btn.setStyleSheet(ui_styles.get_button_style("default"))
        else:
            # 批量下载按钮激活样式（使用primary样式）
            self.batch_download_btn.setStyleSheet(ui_styles.get_button_style("primary"))
            # 视频下载按钮非激活样式（使用default样式）
            self.video_download_btn.setStyleSheet(ui_styles.get_button_style("default"))

    def switch_to_video_download(self):
        """切换到快手视频下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 切换到快手视频下载页面（当前页面，索引2）
            main_window.stacked_widget.setCurrentIndex(2)

    def switch_to_batch_download(self):
        """切换到快手批量下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 切换到快手批量下载页面（新页面，需要添加到stacked_widget）
            # 先检查是否已经存在批量下载页面
            if not hasattr(main_window, 'kuaishou_batch_page'):
                # 创建快手批量下载页面
                main_window.kuaishou_batch_page = KuaishouBatchPage(main_window)
                main_window.stacked_widget.addWidget(main_window.kuaishou_batch_page)

            # 切换到批量下载页面
            batch_index = main_window.stacked_widget.indexOf(main_window.kuaishou_batch_page)
            main_window.stacked_widget.setCurrentIndex(batch_index)


class KuaishouBatchPage(DownloadPageComponent):
    """快手批量下载页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.download_thread = None
        self.is_downloading = False
        self.setup_ui()

    def setup_ui(self):
        """设置UI - 完全按照原版"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """)

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet("""
            QWidget {
                background: transparent;
            }
        """)

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # 标题区域 - 完全按照原版
        title_frame = QFrame()
        title_frame.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.08);
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
        """)
        title_frame.setFixedHeight(60)
        title_layout = QHBoxLayout(title_frame)
        title_layout.setContentsMargins(15, 5, 15, 5)

        # 左侧装饰
        left_decor = QFrame()
        left_decor.setFixedWidth(4)
        left_decor.setStyleSheet("background-color: #6ca6fd; border-radius: 2px;")

        # 创建切换按钮组（替代原来的标题）
        self.button_group_widget = QWidget()
        button_group_layout = QHBoxLayout(self.button_group_widget)
        button_group_layout.setContentsMargins(0, 0, 0, 0)
        button_group_layout.setSpacing(0)  # 按钮之间无间距

        # 快手视频下载按钮
        self.video_download_btn = QPushButton("快手视频下载")
        self.video_download_btn.setMinimumHeight(40)
        self.video_download_btn.clicked.connect(self.switch_to_video_download)

        # 快手批量下载按钮（当前激活状态）
        self.batch_download_btn = QPushButton("快手批量下载")
        self.batch_download_btn.setMinimumHeight(40)
        self.batch_download_btn.clicked.connect(self.switch_to_batch_download)

        # 添加按钮到按钮组
        button_group_layout.addWidget(self.video_download_btn)
        button_group_layout.addWidget(self.batch_download_btn)

        # 设置初始状态（批量下载激活）
        self.update_button_styles(False)

        title_layout.addWidget(left_decor)
        title_layout.addWidget(self.button_group_widget)
        title_layout.addStretch()

        layout.addWidget(title_frame)

        # 用户ID输入区域 - 完全按照原版
        user_id_group = QGroupBox("用户ID")
        user_id_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        user_id_layout = QHBoxLayout(user_id_group)
        user_id_layout.setContentsMargins(12, 15, 12, 12)

        user_id_label = QLabel("输入:")
        user_id_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.user_id_input = QLineEdit()
        self.user_id_input.setPlaceholderText("请输入快手用户ID (例如: 3xq9d8xp)")
        self.user_id_input.setMinimumHeight(42)
        self.user_id_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        user_id_layout.addWidget(user_id_label)
        user_id_layout.addWidget(self.user_id_input, 1)

        layout.addWidget(user_id_group)

        # 保存路径区域 - 完全按照原版
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("路径:")
        path_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.path_input = QLineEdit()
        self.path_input.setPlaceholderText("选择批量下载保存位置...")
        self.path_input.setText(APP_CONFIG['download_paths']['kuaishou_batch'])
        self.path_input.setMinimumHeight(42)
        self.path_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        from ui_styles import UIStyles
        self.ui_styles = UIStyles()

        self.browse_btn = QPushButton("浏览")
        self.browse_btn.setMinimumHeight(42)
        self.browse_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.browse_btn.clicked.connect(self.browse_path)

        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_input, 1)
        path_layout.addWidget(self.browse_btn)

        layout.addWidget(path_group)

        # 操作按钮区域 - 完全按照原版
        button_group = QGroupBox("操作")
        button_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        self.download_btn = QPushButton("开始下载")
        self.download_btn.setMinimumHeight(42)
        self.download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
        self.download_btn.clicked.connect(self.start_download)

        self.clear_btn = QPushButton("清空日志")
        self.clear_btn.setMinimumHeight(42)
        self.clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.clear_btn.clicked.connect(self.clear_log)

        button_layout.addWidget(self.download_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()

        layout.addWidget(button_group)

        # 下载进度区域 - 完全按照原版
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimumHeight(30)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 15px;
                color: #ffffff;
                text-align: center;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """)

        progress_layout.addWidget(self.progress_bar)

        layout.addWidget(progress_group)

        # 下载日志区域 - 完全按照原版
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.log_text = QTextEdit()
        self.log_text.setMinimumHeight(540)  # 增高三倍 (180 * 3)
        self.log_text.setReadOnly(True)
        self.log_text.setStyleSheet("""
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                padding: 12px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                line-height: 1.4;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
        """)

        log_layout.addWidget(self.log_text)
        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)

    def browse_path(self):
        """浏览保存路径"""
        path = QFileDialog.getExistingDirectory(self, "选择保存路径")
        if path:
            self.path_input.setText(path)

    def start_download(self):
        """开始/停止下载"""
        if self.is_downloading:
            # 停止下载
            self.stop_download()
        else:
            # 开始下载
            self.begin_download()

    def begin_download(self):
        """开始批量下载"""
        try:
            user_id = self.user_id_input.text().strip()
            save_path = self.path_input.text().strip()

            if not user_id:
                show_custom_message(self, "警告", "请输入快手用户ID!", "warning")
                return

            if not save_path:
                show_custom_message(self, "警告", "请选择保存路径!", "warning")
                return

            if not os.path.exists(save_path):
                os.makedirs(save_path, exist_ok=True)

            # 检查是否已经在下载
            if hasattr(self, 'download_thread') and self.download_thread and self.download_thread.isRunning():
                self.append_log("已有下载任务在进行中，请等待完成或停止当前任务")
                return

            # 开始下载
            self.is_downloading = True
            self.download_btn.setText("停止下载")
            self.progress_bar.setValue(0)

            # 创建下载线程
            self.download_thread = KuaishouBatchDownloadThread(self)
            self.download_thread.update_log.connect(self.append_log)
            self.download_thread.update_progress.connect(self.update_progress)
            self.download_thread.finished.connect(self.download_finished)
            self.download_thread.error.connect(self.download_error)

            # 设置下载参数
            self.download_thread.set_params(user_id, save_path)
            self.download_thread.start()
            self.append_log("开始批量下载快手视频...")

        except Exception as e:
            self.append_log(f"启动下载失败: {str(e)}")
            self.is_downloading = False
            self.download_btn.setText("开始批量下载")
            import traceback
            traceback.print_exc()

    def stop_download(self):
        """停止下载"""
        try:
            if hasattr(self, 'download_thread') and self.download_thread and self.download_thread.isRunning():
                self.append_log("正在停止下载...")
                # 先尝试优雅停止
                self.download_thread.request_stop()
                if not self.download_thread.wait(3000):  # 等待3秒
                    # 如果优雅停止失败，强制终止
                    self.append_log("强制终止下载线程...")
                    self.download_thread.terminate()
                    self.download_thread.wait()

            self.is_downloading = False
            self.download_btn.setText("开始批量下载")
            self.append_log("下载已停止")
        except Exception as e:
            self.append_log(f"停止下载时出错: {str(e)}")
            self.is_downloading = False
            self.download_btn.setText("开始批量下载")

    def update_progress(self, value):
        """更新进度条"""
        self.progress_bar.setValue(int(value))

    def append_log(self, message):
        """添加日志"""
        self.log_text.append(f"[{self.get_current_time()}] {message}")
        self.log_text.ensureCursorVisible()

    def clear_log(self):
        """清空日志"""
        self.log_text.clear()

    def download_finished(self):
        """下载完成"""
        try:
            self.is_downloading = False
            self.download_btn.setText("开始批量下载")
            self.progress_bar.setValue(100)
            self.append_log("✅ 批量下载完成!")

            # 清理线程引用
            if hasattr(self, 'download_thread'):
                self.download_thread = None
        except Exception as e:
            self.append_log(f"下载完成处理出错: {str(e)}")

    def download_error(self, error_msg):
        """下载错误"""
        try:
            self.is_downloading = False
            self.download_btn.setText("开始批量下载")
            self.append_log(f"❌ 下载失败: {error_msg}")

            # 清理线程引用
            if hasattr(self, 'download_thread'):
                self.download_thread = None

            # 显示错误对话框，但要防止过长的错误信息
            short_error = error_msg.split('\n')[0] if '\n' in error_msg else error_msg
            if len(short_error) > 200:
                short_error = short_error[:200] + "..."
            show_custom_message(self, "下载错误", f"下载失败:\n{short_error}", "error")
        except Exception as e:
            self.append_log(f"错误处理出错: {str(e)}")

    def get_current_time(self):
        """获取当前时间"""
        from datetime import datetime
        return datetime.now().strftime("%H:%M:%S")

    def get_main_window(self):
        """获取主窗口实例"""
        widget = self
        while widget:
            if isinstance(widget, MainWindow):
                return widget
            widget = widget.parent()
        return None

    def update_button_styles(self, video_active):
        """更新按钮样式"""
        if video_active:
            # 视频下载按钮激活样式（使用primary样式）
            self.video_download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
            # 批量下载按钮非激活样式（使用default样式）
            self.batch_download_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        else:
            # 批量下载按钮激活样式（使用primary样式）
            self.batch_download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
            # 视频下载按钮非激活样式（使用default样式）
            self.video_download_btn.setStyleSheet(self.ui_styles.get_button_style("default"))

    def switch_to_video_download(self):
        """切换到快手视频下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 切换到快手视频下载页面（索引2）
            main_window.stacked_widget.setCurrentIndex(2)

    def switch_to_batch_download(self):
        """切换到快手批量下载页面"""
        main_window = self.get_main_window()
        if main_window:
            # 保持在当前页面
            pass


class BilibiliVideoPage(DownloadPageComponent):
    """B站视频下载页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.download_thread = None
        self.is_downloading = False
        self.setup_ui()

    def setup_ui(self):
        """设置UI - 完全按照原版"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """)

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet("""
            QWidget {
                background: transparent;
            }
        """)

        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # 标题区域 - 完全按照原版
        title_frame = QFrame()
        title_frame.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.08);
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
        """)
        title_frame.setFixedHeight(60)
        title_layout = QHBoxLayout(title_frame)
        title_layout.setContentsMargins(15, 5, 15, 5)

        # 左侧装饰
        left_decor = QFrame()
        left_decor.setFixedWidth(4)
        left_decor.setStyleSheet("background-color: #6ca6fd; border-radius: 2px;")

        # 标题
        title_label = QLabel("B站视频下载")
        title_label.setFont(QFont("微软雅黑", 16, QFont.Bold))
        title_label.setStyleSheet("color: #ffffff;")

        title_layout.addWidget(left_decor)
        title_layout.addWidget(title_label)
        title_layout.addStretch()

        layout.addWidget(title_frame)

        # URL输入区域 - 完全按照原版
        url_group = QGroupBox("视频链接")
        url_group.setStyleSheet("""
           QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        url_layout = QHBoxLayout(url_group)
        url_layout.setContentsMargins(12, 15, 12, 12)

        url_label = QLabel("链接:")
        url_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("请输入B站视频链接 (例如: https://www.bilibili.com/video/BV1...)")
        self.url_input.setMinimumHeight(42)
        self.url_input.setStyleSheet("""
             QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(0, 212, 255, 0.5) !important;
            }
        """)

        url_layout.addWidget(url_label)
        url_layout.addWidget(self.url_input, 1)

        layout.addWidget(url_group)

        # 保存路径区域 - 完全按照原版
        path_group = QGroupBox("保存路径")
        path_group.setStyleSheet("""
             QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        path_layout = QHBoxLayout(path_group)
        path_layout.setContentsMargins(12, 15, 12, 12)

        path_label = QLabel("路径:")
        path_label.setStyleSheet("color: #ffffff; font-weight: normal;")

        self.path_input = QLineEdit()
        self.path_input.setPlaceholderText("选择视频保存位置...")
        self.path_input.setText(APP_CONFIG['download_paths']['bilibili_video'])
        self.path_input.setMinimumHeight(42)
        self.path_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.08) !important;
                border: 2px solid rgba(255, 255, 255, 0.15) !important;
                border-radius: 12px !important;
                color: #ffffff !important;
                padding: 12px 16px !important;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.12) !important;
                border: 2px solid rgba(255, 107, 157, 0.5) !important;
            }
        """)

        self.browse_btn = QPushButton("浏览")
        self.browse_btn.setMinimumHeight(42)
        self.browse_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.browse_btn.clicked.connect(self.browse_path)
        path_layout.addWidget(path_label)
        path_layout.addWidget(self.path_input, 1)
        path_layout.addWidget(self.browse_btn)
        layout.addWidget(path_group)
        # 控制按钮区域 - 按照快手页面布局
        button_group = QGroupBox("操作")
        button_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        button_layout = QHBoxLayout(button_group)
        button_layout.setContentsMargins(12, 15, 12, 12)

        # 下载按钮
        self.download_btn = QPushButton("开始下载")
        self.download_btn.setMinimumHeight(42)
        self.download_btn.setStyleSheet(self.ui_styles.get_button_style("primary"))
        self.download_btn.clicked.connect(self.start_download)
        self.clear_btn = QPushButton("清空日志")
        self.clear_btn.setMinimumHeight(42)
        self.clear_btn.setStyleSheet(self.ui_styles.get_button_style("default"))
        self.clear_btn.clicked.connect(self.clear_log)
        button_layout.addWidget(self.download_btn)
        button_layout.addWidget(self.clear_btn)
        button_layout.addStretch()
        layout.addWidget(button_group)

        # 进度条区域 - 完全按照快手页面
        progress_group = QGroupBox("下载进度")
        progress_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        progress_layout = QVBoxLayout(progress_group)
        progress_layout.setContentsMargins(12, 15, 12, 12)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimumHeight(30)
        self.progress_bar.setMaximum(100)
        self.progress_bar.setValue(0)
        self.progress_bar.setStyleSheet("""
            QProgressBar {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 15px;
                text-align: center;
                color: #ffffff;
                font-weight: bold;
                font-size: 11pt;
            }
            QProgressBar::chunk {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00d4ff, stop:1 #0099cc);
                border-radius: 13px;
            }
        """)

        progress_layout.addWidget(self.progress_bar)

        layout.addWidget(progress_group)

        # 日志区域 - 完全按照原版
        log_group = QGroupBox("下载日志")
        log_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 255, 255, 0.15);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        log_layout = QVBoxLayout(log_group)
        log_layout.setContentsMargins(12, 15, 12, 12)

        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setMinimumHeight(200)
        self.log_text.setStyleSheet("""
            QTextEdit {
                background: rgba(0, 0, 0, 0.3);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                padding: 10px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                line-height: 1.4;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
        """)

        log_layout.addWidget(self.log_text, 1)

        layout.addWidget(log_group)

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)

    def browse_path(self):
        """浏览保存路径"""
        path = QFileDialog.getExistingDirectory(self, "选择保存路径")
        if path:
            self.path_input.setText(path)

    def start_download(self):
        """开始/停止下载"""
        if self.is_downloading:
            # 停止下载
            self.stop_download()
        else:
            # 开始下载
            self.begin_download()

    def begin_download(self):
        """开始下载"""
        url = self.url_input.text().strip()
        save_path = self.path_input.text().strip()

        if not url:
            show_custom_message(self, "警告", "请输入B站视频链接!", "warning")
            return

        if not save_path:
            show_custom_message(self, "警告", "请选择保存路径!", "warning")
            return

        if not os.path.exists(save_path):
            os.makedirs(save_path, exist_ok=True)

        # 开始下载
        self.is_downloading = True
        self.download_btn.setText("停止下载")
        self.progress_bar.setValue(0)

        # 创建下载线程
        self.download_thread = DownloadThread()
        self.download_thread.update_log.connect(self.append_log)
        self.download_thread.update_progress.connect(self.update_progress)
        self.download_thread.finished.connect(self.download_finished)
        self.download_thread.error.connect(self.download_error)

        # 设置下载参数 - 使用主窗口的下载器实例
        main_window = self.get_main_window()
        if main_window and hasattr(main_window, 'downloader_core'):
            downloader = main_window.downloader_core
        else:
            from downloader_core import DownloaderCore
            downloader = DownloaderCore()

        self.download_thread.set_params(
            downloader.download_bilibili_video,
            (url, save_path, self.download_thread.update_progress.emit, self.download_thread.update_log.emit)
        )

        self.download_thread.start()
        self.append_log("开始下载B站视频...")

    def stop_download(self):
        """停止下载"""
        if self.download_thread and self.download_thread.isRunning():
            # 先尝试优雅停止
            self.download_thread.request_stop()
            if not self.download_thread.wait(3000):  # 等待3秒
                # 如果优雅停止失败，强制终止
                self.download_thread.terminate()
                self.download_thread.wait()

        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.progress_bar.setValue(0)
        self.append_log("下载已停止")

    def update_progress(self, value):
        """更新进度"""
        self.progress_bar.setValue(value)

    def append_log(self, message):
        """添加日志"""
        self.log_text.append(f"[{self.get_current_time()}] {message}")
        self.log_text.ensureCursorVisible()

    def clear_log(self):
        """清空日志"""
        self.log_text.clear()

    def download_finished(self):
        """下载完成"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.progress_bar.setValue(100)
        self.append_log("下载完成!")

    def download_error(self, error_msg):
        """下载错误"""
        self.is_downloading = False
        self.download_btn.setText("开始下载")
        self.progress_bar.setValue(0)
        self.append_log(f"下载失败: {error_msg}")
        show_custom_message(self, "错误", f"下载失败: {error_msg}", "error")

    def get_current_time(self):
        """获取当前时间"""
        from datetime import datetime
        return datetime.now().strftime("%H:%M:%S")

    def open_folder(self):
        """打开保存文件夹"""
        save_path = self.path_input.text().strip()
        if save_path and os.path.exists(save_path):
            import subprocess
            subprocess.Popen(f'explorer "{save_path}"')
        else:
            show_custom_message(self, "警告", "保存路径不存在！", "warning")

    def get_main_window(self):
        """获取主窗口实例"""
        widget = self
        while widget:
            if isinstance(widget, MainWindow):
                return widget
            widget = widget.parent()
        return None


class HelpPage(DownloadPageComponent):
    """使用说明页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()

    def setup_ui(self):
        """设置UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(10)

        # 标题区域
        title_frame = QFrame()
        title_frame.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.08);
                border-radius: 12px;
                border: 2px solid rgba(255, 255, 255, 0.15);
            }
        """)
        title_frame.setFixedHeight(60)
        title_layout = QHBoxLayout(title_frame)
        title_layout.setContentsMargins(15, 5, 15, 5)

        # 左侧装饰
        left_decor = QFrame()
        left_decor.setFixedWidth(4)
        left_decor.setStyleSheet("background-color: #6ca6fd; border-radius: 2px;")

        # 标题
        title_label = QLabel("使用说明")
        title_label.setFont(QFont("微软雅黑", 16, QFont.Bold))

        title_layout.addWidget(left_decor)
        title_layout.addWidget(title_label)
        title_layout.addStretch()

        layout.addWidget(title_frame)

        # 说明文档区域
        help_group = QGroupBox("使用指南")
        help_layout = QVBoxLayout(help_group)
        help_layout.setContentsMargins(12, 15, 12, 12)

        # 创建只读文本框
        self.help_text = QTextEdit()
        self.help_text.setReadOnly(True)
        self.help_text.setMinimumHeight(500)

        # 加载图片到文档中
        self.load_help_images()
        self.help_text.setStyleSheet("""
            QTextEdit {
                background: rgba(255, 255, 255, 0.08);
                color: #ffffff;
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                padding: 15px;
                font-family: 'Microsoft YaHei UI', sans-serif;
                font-size: 13pt;
                line-height: 1.8;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
        """)

        # 获取图片路径
        import os
        current_dir = os.path.dirname(os.path.abspath(__file__))
        image_path = os.path.join(current_dir, "cookie_example.png").replace("\\", "/")

        # 设置说明文档内容
        help_content = f"""
<h2 style="color: #00d4ff; margin-bottom: 15px;">📖 下载器使用说明</h2>

<h3 style="color: #6ca6fd; margin-top: 20px; margin-bottom: 10px;">🎬 视频图片下载</h3>
<p style="margin-bottom: 10px;">对于精选区,点击视频后直接复制浏览器顶部的链接即可。</p>
<p style="margin-bottom: 10px;">对于刷到的某个用户的视频，需要点进用户主页后再寻找到具体的视频复制链接</p>
<p style="margin-bottom: 10px;">图片下载同理，点进用户主页后寻找到图片集，然后复制链接</p>

<h3 style="color: #6ca6fd; margin-top: 20px; margin-bottom: 10px;">⚙️ 设置说明</h3>
<p style="margin-bottom: 10px;">• <b>Cookie设置：</b>用于访问需要登录的内容</p>
<p style="margin-bottom: 10px;">• <b>默认下载路径：</b>设置所有下载的默认保存位置</p>
<p style="margin-bottom: 15px;">• 设置修改后会自动保存</p>

<h4 style="color: #6ca6fd; margin-top: 15px; margin-bottom: 10px;">Cookie获取方法：</h4>
<p style="margin-bottom: 10px;">1. 打开浏览器开发者工具（F12）</p>
<p style="margin-bottom: 10px;">2. 切换到Network（网络）标签页</p>
<p style="margin-bottom: 10px;">3. 访问目标网站并登录</p>
<p style="margin-bottom: 10px;">4. 在请求中找到Cookie信息</p>
<div style="text-align: center; margin: 15px 0;">
<img src="cookie_example.png"  style="width: 120%; max-width: 120%; height: auto; border: 2px solid rgba(255,255,255,0.3); border-radius: 8px; display: block; margin: 0 auto;">
</div>


<h3 style="color: #6ca6fd; margin-top: 20px; margin-bottom: 10px;">⚠️ 注意事项</h3>
<p style="margin-bottom: 10px;">• 请确保有足够的磁盘空间</p>
<p style="margin-bottom: 10px;">• 下载的内容仅供个人学习使用</p>
<p style="margin-bottom: 10px;">• 请遵守相关平台的使用条款</p>
<p style="margin-bottom: 10px;">• 不支持长时间下载，开源免费，盈利必究</p>
<p style="margin-bottom: 10px;">• 如果遇上获取不到数据的情况，请及时联系软件作者</p>

<hr style="margin: 20px 0; border: 1px solid rgba(255,255,255,0.2);">
<p style="text-align: center; color: rgba(255,255,255,0.6); font-size: 12pt;">
© 2025 中鄂智创 | 版本 v2.1 Pro
</p>
        """

        self.help_text.setHtml(help_content)

        help_layout.addWidget(self.help_text)
        layout.addWidget(help_group)

    def load_help_images(self):
        """加载帮助页面的图片"""
        try:
            import os

            current_dir = os.path.dirname(os.path.abspath(__file__))
            image_path = os.path.join(current_dir, "cookie_example.png")

            if os.path.exists(image_path):
                # 加载图片
                pixmap = QPixmap(image_path)
                if not pixmap.isNull():
                    # 缩放图片 - 调大尺寸以占满容器宽度
                    scaled_pixmap = pixmap.scaled(800, 600, Qt.KeepAspectRatio, Qt.SmoothTransformation)

                    # 将图片添加到文档资源中
                    document = self.help_text.document()
                    document.addResource(QTextDocument.ImageResource,
                                       QUrl("cookie_example.png"), scaled_pixmap)
        except Exception:
            pass  # 静默处理图片加载失败


class SettingsPage(DownloadPageComponent):
    """设置页面"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()

    def setup_ui(self):
        """设置UI"""
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: none;
                background: transparent;
            }
            QScrollArea > QWidget > QWidget {
                background: transparent;
            }
            QScrollBar:vertical {
                background: rgba(255, 255, 255, 0.1);
                width: 12px;
                border-radius: 6px;
                margin: 0;
            }
            QScrollBar::handle:vertical {
                background: rgba(255, 255, 255, 0.3);
                border-radius: 6px;
                min-height: 20px;
            }
            QScrollBar::handle:vertical:hover {
                background: rgba(255, 255, 255, 0.5);
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                border: none;
                background: none;
            }
        """)

        # 创建滚动内容容器
        scroll_content = QWidget()
        scroll_content.setStyleSheet("background: transparent;")
        layout = QVBoxLayout(scroll_content)
        layout.setContentsMargins(40, 30, 40, 30)
        layout.setSpacing(25)

        # 页面标题
        title = QLabel("⚙️ 设置")
        title.setFont(QFont("Microsoft YaHei UI", 16, QFont.Bold))
        title.setStyleSheet("color: #ffffff; margin-bottom: 10px;")
        layout.addWidget(title)

        # 默认下载路径
        path_group, self.default_path_input, self.path_browse_btn = self.create_input_group(
            "默认下载路径", "设置默认下载路径...", browse_button=True
        )
        self.default_path_input.setText(APP_CONFIG['default_download_path'])
        self.path_browse_btn.clicked.connect(self.browse_default_path)
        layout.addWidget(path_group)

        # 抖音Cookie设置区域
        douyin_cookie_group = QGroupBox("🍪 抖音Cookie设置")
        douyin_cookie_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(0, 201, 255, 0.4);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00c9ff, stop:0.5 #667eea, stop:1 #764ba2);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        douyin_cookie_group_layout = QVBoxLayout(douyin_cookie_group)
        douyin_cookie_group_layout.setContentsMargins(20, 25, 20, 20)
        douyin_cookie_group_layout.setSpacing(20)

        # 抖音Cookie文件选择
        douyin_cookie_file_widget = QWidget()
        douyin_cookie_file_layout = QVBoxLayout(douyin_cookie_file_widget)
        douyin_cookie_file_layout.setContentsMargins(0, 0, 0, 0)
        douyin_cookie_file_layout.setSpacing(8)

        douyin_cookie_file_label = QLabel("抖音Cookie文件:")
        douyin_cookie_file_label.setStyleSheet("color: #ffffff; font-weight: bold; font-size: 12pt; text-shadow: 0 0 5px rgba(255,255,255,0.5);")

        douyin_cookie_file_row = QHBoxLayout()
        self.douyin_cookie_input = QLineEdit()
        self.douyin_cookie_input.setPlaceholderText("选择抖音Cookie文件或直接粘贴Cookie内容...")
        self.douyin_cookie_input.setMinimumHeight(40)
        self.douyin_cookie_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                color: #ffffff !important;
                padding: 8px 12px;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.15);
                border: 2px solid rgba(0, 201, 255, 0.6);
            }
        """)

        self.douyin_cookie_browse_btn = QPushButton("浏览")
        self.douyin_cookie_browse_btn.setMinimumHeight(40)
        self.douyin_cookie_browse_btn.setMinimumWidth(80)
        self.douyin_cookie_browse_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(0, 122, 255, 0.8), stop:1 rgba(0, 122, 255, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(0, 122, 255, 1.0), stop:1 rgba(0, 122, 255, 0.8));
            }
        """)
        self.douyin_cookie_browse_btn.clicked.connect(self.browse_douyin_cookie_file)

        douyin_cookie_file_row.addWidget(self.douyin_cookie_input)
        douyin_cookie_file_row.addWidget(self.douyin_cookie_browse_btn)

        douyin_cookie_file_layout.addWidget(douyin_cookie_file_label)
        douyin_cookie_file_layout.addLayout(douyin_cookie_file_row)

        # 抖音Cookie操作按钮
        douyin_cookie_btn_layout = QHBoxLayout()
        douyin_cookie_btn_layout.setSpacing(10)

        self.apply_douyin_cookie_btn = QPushButton("✅ 应用抖音Cookie")
        self.apply_douyin_cookie_btn.setMinimumHeight(40)
        self.apply_douyin_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 0.8), stop:1 rgba(52, 199, 89, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 1.0), stop:1 rgba(52, 199, 89, 0.8));
            }
        """)
        self.apply_douyin_cookie_btn.clicked.connect(self.apply_douyin_cookie)

        self.reset_douyin_cookie_btn = QPushButton("🔄 重置抖音Cookie")
        self.reset_douyin_cookie_btn.setMinimumHeight(40)
        self.reset_douyin_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 0.8), stop:1 rgba(255, 59, 48, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 1.0), stop:1 rgba(255, 59, 48, 0.8));
            }
        """)
        self.reset_douyin_cookie_btn.clicked.connect(self.reset_douyin_cookie)

        douyin_cookie_btn_layout.addWidget(self.apply_douyin_cookie_btn)
        douyin_cookie_btn_layout.addWidget(self.reset_douyin_cookie_btn)

        douyin_cookie_group_layout.addWidget(douyin_cookie_file_widget)
        douyin_cookie_group_layout.addLayout(douyin_cookie_btn_layout)
        layout.addWidget(douyin_cookie_group)

        # 快手Cookie设置区域
        kuaishou_cookie_group = QGroupBox("⚡ 快手Cookie设置")
        kuaishou_cookie_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 193, 7, 0.4);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ffc107, stop:0.5 #ff9800, stop:1 #ff5722);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        kuaishou_cookie_group_layout = QVBoxLayout(kuaishou_cookie_group)
        kuaishou_cookie_group_layout.setContentsMargins(20, 25, 20, 20)
        kuaishou_cookie_group_layout.setSpacing(20)

        # 快手Cookie文件选择
        kuaishou_cookie_file_widget = QWidget()
        kuaishou_cookie_file_layout = QVBoxLayout(kuaishou_cookie_file_widget)
        kuaishou_cookie_file_layout.setContentsMargins(0, 0, 0, 0)
        kuaishou_cookie_file_layout.setSpacing(8)

        kuaishou_cookie_file_label = QLabel("快手Cookie文件:")
        kuaishou_cookie_file_label.setStyleSheet("color: #ffffff; font-weight: bold; font-size: 12pt; text-shadow: 0 0 5px rgba(255,255,255,0.5);")

        kuaishou_cookie_file_row = QHBoxLayout()
        self.kuaishou_cookie_input = QLineEdit()
        self.kuaishou_cookie_input.setPlaceholderText("选择快手Cookie文件或直接粘贴Cookie内容...")
        self.kuaishou_cookie_input.setMinimumHeight(40)
        self.kuaishou_cookie_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                color: #ffffff !important;
                padding: 8px 12px;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.15);
                border: 2px solid rgba(255, 193, 7, 0.6);
            }
        """)

        self.kuaishou_cookie_browse_btn = QPushButton("浏览")
        self.kuaishou_cookie_browse_btn.setMinimumHeight(40)
        self.kuaishou_cookie_browse_btn.setMinimumWidth(80)
        self.kuaishou_cookie_browse_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 193, 7, 0.8), stop:1 rgba(255, 193, 7, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 193, 7, 1.0), stop:1 rgba(255, 193, 7, 0.8));
            }
        """)
        self.kuaishou_cookie_browse_btn.clicked.connect(self.browse_kuaishou_cookie_file)

        kuaishou_cookie_file_row.addWidget(self.kuaishou_cookie_input)
        kuaishou_cookie_file_row.addWidget(self.kuaishou_cookie_browse_btn)

        kuaishou_cookie_file_layout.addWidget(kuaishou_cookie_file_label)
        kuaishou_cookie_file_layout.addLayout(kuaishou_cookie_file_row)

        # 快手Cookie操作按钮
        kuaishou_cookie_btn_layout = QHBoxLayout()
        kuaishou_cookie_btn_layout.setSpacing(10)

        self.apply_kuaishou_cookie_btn = QPushButton("✅ 应用快手Cookie")
        self.apply_kuaishou_cookie_btn.setMinimumHeight(40)
        self.apply_kuaishou_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 0.8), stop:1 rgba(52, 199, 89, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 1.0), stop:1 rgba(52, 199, 89, 0.8));
            }
        """)
        self.apply_kuaishou_cookie_btn.clicked.connect(self.apply_kuaishou_cookie)

        self.reset_kuaishou_cookie_btn = QPushButton("🔄 重置快手Cookie")
        self.reset_kuaishou_cookie_btn.setMinimumHeight(40)
        self.reset_kuaishou_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 0.8), stop:1 rgba(255, 59, 48, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 1.0), stop:1 rgba(255, 59, 48, 0.8));
            }
        """)
        self.reset_kuaishou_cookie_btn.clicked.connect(self.reset_kuaishou_cookie)

        kuaishou_cookie_btn_layout.addWidget(self.apply_kuaishou_cookie_btn)
        kuaishou_cookie_btn_layout.addWidget(self.reset_kuaishou_cookie_btn)

        kuaishou_cookie_group_layout.addWidget(kuaishou_cookie_file_widget)
        kuaishou_cookie_group_layout.addLayout(kuaishou_cookie_btn_layout)
        layout.addWidget(kuaishou_cookie_group)

        # B站Cookie设置区域
        bilibili_cookie_group = QGroupBox("📺 B站Cookie设置")
        bilibili_cookie_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 107, 157, 0.4);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff6b9d, stop:0.5 #c44569, stop:1 #f8b500);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        bilibili_cookie_group_layout = QVBoxLayout(bilibili_cookie_group)
        bilibili_cookie_group_layout.setContentsMargins(20, 25, 20, 20)
        bilibili_cookie_group_layout.setSpacing(20)

        # B站Cookie文件选择
        bilibili_cookie_file_widget = QWidget()
        bilibili_cookie_file_layout = QVBoxLayout(bilibili_cookie_file_widget)
        bilibili_cookie_file_layout.setContentsMargins(0, 0, 0, 0)
        bilibili_cookie_file_layout.setSpacing(8)

        bilibili_cookie_file_label = QLabel("B站Cookie文件:")
        bilibili_cookie_file_label.setStyleSheet("color: #ffffff; font-weight: bold; font-size: 12pt; text-shadow: 0 0 5px rgba(255,255,255,0.5);")

        bilibili_cookie_file_row = QHBoxLayout()
        self.bilibili_cookie_input = QLineEdit()
        self.bilibili_cookie_input.setPlaceholderText("选择B站Cookie文件或直接粘贴Cookie内容...")
        self.bilibili_cookie_input.setMinimumHeight(40)
        self.bilibili_cookie_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                color: #ffffff !important;
                padding: 8px 12px;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.15);
                border: 2px solid rgba(255, 107, 157, 0.6);
            }
        """)

        self.bilibili_cookie_browse_btn = QPushButton("浏览")
        self.bilibili_cookie_browse_btn.setMinimumHeight(40)
        self.bilibili_cookie_browse_btn.setMinimumWidth(80)
        self.bilibili_cookie_browse_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 107, 157, 0.8), stop:1 rgba(255, 107, 157, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 107, 157, 1.0), stop:1 rgba(255, 107, 157, 0.8));
            }
        """)
        self.bilibili_cookie_browse_btn.clicked.connect(self.browse_bilibili_cookie_file)

        bilibili_cookie_file_row.addWidget(self.bilibili_cookie_input)
        bilibili_cookie_file_row.addWidget(self.bilibili_cookie_browse_btn)

        bilibili_cookie_file_layout.addWidget(bilibili_cookie_file_label)
        bilibili_cookie_file_layout.addLayout(bilibili_cookie_file_row)

        # B站Cookie操作按钮
        bilibili_cookie_btn_layout = QHBoxLayout()
        bilibili_cookie_btn_layout.setSpacing(10)

        self.apply_bilibili_cookie_btn = QPushButton("✅ 应用B站Cookie")
        self.apply_bilibili_cookie_btn.setMinimumHeight(40)
        self.apply_bilibili_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 0.8), stop:1 rgba(52, 199, 89, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 1.0), stop:1 rgba(52, 199, 89, 0.8));
            }
        """)
        self.apply_bilibili_cookie_btn.clicked.connect(self.apply_bilibili_cookie)

        self.reset_bilibili_cookie_btn = QPushButton("🔄 重置B站Cookie")
        self.reset_bilibili_cookie_btn.setMinimumHeight(40)
        self.reset_bilibili_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 0.8), stop:1 rgba(255, 59, 48, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 1.0), stop:1 rgba(255, 59, 48, 0.8));
            }
        """)
        self.reset_bilibili_cookie_btn.clicked.connect(self.reset_bilibili_cookie)

        bilibili_cookie_btn_layout.addWidget(self.apply_bilibili_cookie_btn)
        bilibili_cookie_btn_layout.addWidget(self.reset_bilibili_cookie_btn)

        bilibili_cookie_group_layout.addWidget(bilibili_cookie_file_widget)
        bilibili_cookie_group_layout.addLayout(bilibili_cookie_btn_layout)
        layout.addWidget(bilibili_cookie_group)

        # 使用说明
        info_text = QLabel("""
        <b>使用说明：</b><br>
        1. Cookie文件用于访问需要登录的内容<br>
        2. 可以从浏览器导出Cookie文件<br>
        3. 默认下载路径会应用到所有下载页面<br>
        4. 设置修改后会自动保存
        """)
        info_text.setFont(QFont("Microsoft YaHei UI", 10))
        info_text.setStyleSheet("color: #ffffff; padding: 20px; background: rgba(255, 255, 255, 0.08); border-radius: 8px; border: 1px solid rgba(0, 212, 255, 0.3);")
        info_text.setWordWrap(True)
        layout.addWidget(info_text)

        # 付费区设置区域（简化版）
        weimiquan_group = QGroupBox("🌸 付费区设置")
        weimiquan_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 107, 157, 0.4);
                border-radius: 12px;
                margin: 10px 0;
                background: rgba(255, 255, 255, 0.08);
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff6b9d, stop:0.5 #c44569, stop:1 #f8b500);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
            }
        """)
        weimiquan_layout = QVBoxLayout(weimiquan_group)
        weimiquan_layout.setContentsMargins(20, 25, 20, 20)
        weimiquan_layout.setSpacing(20)

        # 代理设置行
        proxy_row_layout = QHBoxLayout()
        proxy_row_layout.setSpacing(20)

        # 代理主机
        proxy_host_widget = QWidget()
        proxy_host_layout = QVBoxLayout(proxy_host_widget)
        proxy_host_layout.setContentsMargins(0, 0, 0, 0)
        proxy_host_layout.setSpacing(8)

        proxy_host_label = QLabel("代理主机:")
        proxy_host_label.setStyleSheet("color: #ffffff !important; font-weight: bold; font-size: 12pt; text-shadow: 0 0 5px rgba(255,255,255,0.5);")
        self.proxy_host_input = QLineEdit("127.0.0.1")
        self.proxy_host_input.setMinimumHeight(40)
        self.proxy_host_input.setStyleSheet("""
            QLineEdit {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                color: #ffffff;
                padding: 8px 12px;
                font-size: 10pt;
            }
            QLineEdit:focus {
                background: rgba(255, 255, 255, 0.15);
                border: 2px solid rgba(255, 107, 157, 0.6);
            }
        """)

        proxy_host_layout.addWidget(proxy_host_label)
        proxy_host_layout.addWidget(self.proxy_host_input)

        # 代理端口
        proxy_port_widget = QWidget()
        proxy_port_layout = QVBoxLayout(proxy_port_widget)
        proxy_port_layout.setContentsMargins(0, 0, 0, 0)
        proxy_port_layout.setSpacing(8)

        proxy_port_label = QLabel("代理端口:")
        proxy_port_label.setStyleSheet("color: #ffffff !important; font-weight: bold; font-size: 12pt; text-shadow: 0 0 5px rgba(255,255,255,0.5);")
        self.proxy_port_input = QSpinBox()
        self.proxy_port_input.setRange(1, 65535)
        self.proxy_port_input.setValue(7890)
        self.proxy_port_input.setMinimumHeight(40)
        self.proxy_port_input.setMinimumWidth(120)
        self.proxy_port_input.setAlignment(Qt.AlignLeft)
        self.proxy_port_input.setButtonSymbols(QSpinBox.NoButtons)
        self.proxy_port_input.setStyleSheet("""
            QSpinBox {
                background: rgba(255, 255, 255, 0.1);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                color: #ffffff;
                padding-top: -6px;
                padding-bottom: 12px;
                padding-left: 12px;
                font-size: 10pt;
                text-align: left;
            }
            QSpinBox:focus {
                background: rgba(255, 255, 255, 0.15);
                border: 2px solid rgba(255, 107, 157, 0.6);
            }
        """)

        proxy_port_layout.addWidget(proxy_port_label)
        proxy_port_layout.addWidget(self.proxy_port_input)

        proxy_row_layout.addWidget(proxy_host_widget, 2)
        proxy_row_layout.addWidget(proxy_port_widget, 1)

        # 微密圈Cookie设置（简化版）
        cookie_widget = QWidget()
        cookie_layout = QVBoxLayout(cookie_widget)
        cookie_layout.setContentsMargins(0, 0, 0, 0)
        cookie_layout.setSpacing(8)

        cookie_label = QLabel("付费区Cookie（可选，留空使用默认）:")
        cookie_label.setStyleSheet("color: #ffffff !important; font-weight: bold; font-size: 12pt; text-shadow: 0 0 5px rgba(255,255,255,0.5);")
        self.weimiquan_cookie_text = QPlainTextEdit()
        self.weimiquan_cookie_text.setMinimumHeight(80)
        self.weimiquan_cookie_text.setMaximumHeight(120)
        self.weimiquan_cookie_text.setPlaceholderText("粘贴Cookie内容，格式: key1=value1; key2=value2; ...")
        self.weimiquan_cookie_text.setStyleSheet("""
            QPlainTextEdit {
                background: rgba(0, 0, 0, 0.4);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                color: #ffffff;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 9pt;
                padding: 8px;
            }
            QPlainTextEdit:focus {
                border: 2px solid rgba(255, 107, 157, 0.6);
            }
        """)

        cookie_layout.addWidget(cookie_label)
        cookie_layout.addWidget(self.weimiquan_cookie_text)

        # 微密圈Cookie操作按钮
        weimiquan_cookie_btn_layout = QHBoxLayout()
        weimiquan_cookie_btn_layout.setSpacing(10)

        self.apply_weimiquan_cookie_btn = QPushButton("✅ 应用Cookie")
        self.apply_weimiquan_cookie_btn.setMinimumHeight(40)
        self.apply_weimiquan_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 0.8), stop:1 rgba(52, 199, 89, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(52, 199, 89, 1.0), stop:1 rgba(52, 199, 89, 0.8));
            }
        """)
        self.apply_weimiquan_cookie_btn.clicked.connect(self.apply_weimiquan_cookie)

        self.reset_weimiquan_cookie_btn = QPushButton("🔄 重置Cookie")
        self.reset_weimiquan_cookie_btn.setMinimumHeight(40)
        self.reset_weimiquan_cookie_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 0.8), stop:1 rgba(255, 59, 48, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 59, 48, 1.0), stop:1 rgba(255, 59, 48, 0.8));
            }
        """)
        self.reset_weimiquan_cookie_btn.clicked.connect(self.reset_weimiquan_cookie)

        weimiquan_cookie_btn_layout.addWidget(self.apply_weimiquan_cookie_btn)
        weimiquan_cookie_btn_layout.addWidget(self.reset_weimiquan_cookie_btn)

        # 密码设置按钮
        password_btn_layout = QHBoxLayout()
        password_btn_layout.setSpacing(15)

        self.change_password_btn = QPushButton("🔐 更改访问密码")
        self.change_password_btn.setMinimumHeight(40)
        self.change_password_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 149, 0, 0.8), stop:1 rgba(255, 149, 0, 0.6));
                border: none;
                border-radius: 8px;
                color: white;
                font-weight: bold;
                font-size: 10pt;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 149, 0, 1.0), stop:1 rgba(255, 149, 0, 0.8));
            }
        """)
        self.change_password_btn.clicked.connect(self.change_password)
        password_btn_layout.addWidget(self.change_password_btn)

        # 添加所有组件到微密圈布局
        weimiquan_layout.addLayout(proxy_row_layout)
        weimiquan_layout.addWidget(cookie_widget)
        weimiquan_layout.addLayout(weimiquan_cookie_btn_layout)
        weimiquan_layout.addLayout(password_btn_layout)

        layout.addWidget(weimiquan_group)

        # 霓虹粒子特效设置
        self.neon_particle_group = self.create_neon_particle_settings()
        layout.addWidget(self.neon_particle_group)

        layout.addStretch()

        # 设置滚动区域
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)

        # 加载已保存的微密圈设置
        self.load_weimiquan_settings()

        # 加载霓虹粒子特效设置
        self.load_neon_particle_settings()

    def browse_default_path(self):
        """浏览默认路径"""
        path = QFileDialog.getExistingDirectory(self, "选择默认下载路径")
        if path:
            self.default_path_input.setText(path)

    def browse_douyin_cookie_file(self):
        """浏览抖音Cookie文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择抖音Cookie文件", "", "JSON文件 (*.json);;文本文件 (*.txt);;所有文件 (*)"
        )
        if file_path:
            self.douyin_cookie_input.setText(file_path)

    def apply_douyin_cookie(self):
        """应用抖音Cookie"""
        cookie_input = self.douyin_cookie_input.text().strip()
        if not cookie_input:
            show_custom_message(self, "警告", "请输入抖音Cookie内容或选择Cookie文件!", "warning")
            return

        try:
            # 验证Cookie格式并解析
            from cookie_manager import CookieManager
            cookie_manager = CookieManager()

            cookie_content = ""
            if os.path.exists(cookie_input):
                # 如果是文件路径，读取文件
                try:
                    with open(cookie_input, 'r', encoding='utf-8') as f:
                        cookie_content = f.read().strip()
                except UnicodeDecodeError:
                    show_custom_message(self, "错误", "❌ 抖音Cookie文件编码错误！\n请确保文件使用UTF-8编码保存", "error")
                    return
                except Exception as e:
                    show_custom_message(self, "错误", f"❌ 读取抖音Cookie文件失败！\n{str(e)}", "error")
                    return
            else:
                # 直接使用输入的Cookie字符串
                cookie_content = cookie_input

            if not cookie_content:
                show_custom_message(self, "错误", "❌ 抖音Cookie内容为空！", "error")
                return

            # 解析Cookie
            try:
                cookies_dict = cookie_manager.parse_cookie_string(cookie_content)
                if not cookies_dict:
                    show_custom_message(self, "错误", "❌ 抖音Cookie格式错误！\n\n📝 支持的格式：\n• key1=value1; key2=value2\n• key1=value1\n  key2=value2\n• JSON格式", "error")
                    return
            except Exception as e:
                show_custom_message(self, "错误", f"❌ 抖音Cookie解析失败！\n格式可能不正确：{str(e)}\n\n📝 支持的格式：\n• key1=value1; key2=value2\n• key1=value1\n  key2=value2", "error")
                return

            # 获取主窗口并应用Cookie
            main_window = self.get_main_window()
            if main_window and hasattr(main_window, 'downloader_core'):
                # 使用主窗口的下载核心
                main_window.downloader_core.set_custom_cookies(cookies_dict, "douyin")
                cookie_count = len(cookies_dict)
            else:
                # 直接保存Cookie
                success = cookie_manager.save_douyin_cookies(cookies_dict)
                if not success:
                    show_custom_message(self, "错误", "❌ 抖音Cookie保存失败！", "error")
                    return
                cookie_count = len(cookies_dict)

            # 显示成功消息
            show_custom_message(self, "成功", f"✅ 抖音Cookie应用成功！\n\n📊 解析结果：\n• 成功解析 {cookie_count} 个Cookie项\n• Cookie已自动保存到本地文件\n• 下次启动时会自动加载", "success")

        except FileNotFoundError:
            show_custom_message(self, "错误", "❌ 抖音Cookie文件不存在！\n请检查文件路径是否正确", "error")
        except Exception as e:
            show_custom_message(self, "错误", f"❌ 应用抖音Cookie时发生未知错误：\n{str(e)}", "error")

    def reset_douyin_cookie(self):
        """重置抖音Cookie"""
        try:
            # 清空输入框
            self.douyin_cookie_input.clear()

            # 尝试清除保存的Cookie文件
            from cookie_manager import CookieManager
            cookie_manager = CookieManager()

            # 清除Cookie文件
            success = cookie_manager.save_douyin_cookies({})  # 保存空Cookie字典

            # 清除内存中的Cookie
            main_window = self.get_main_window()
            if main_window and hasattr(main_window, 'downloader_core'):
                main_window.downloader_core.set_custom_cookies({}, "douyin")

            if success:
                show_custom_message(self, "成功", f"✅ 抖音Cookie重置成功！\n\n🔄 重置内容：\n• 清空了Cookie输入框\n• 清除了本地保存的Cookie文件\n• 清除了内存中的Cookie缓存\n• 恢复为默认Cookie配置", "success")
            else:
                show_custom_message(self, "警告", "⚠️ Cookie输入框已清空\n但清除本地Cookie文件时出现问题", "warning")

        except Exception as e:
            # 即使出错，也要清空输入框
            self.douyin_cookie_input.clear()
            show_custom_message(self, "警告", f"⚠️ Cookie输入框已清空\n但重置过程中出现错误：{str(e)}", "warning")

    def browse_kuaishou_cookie_file(self):
        """浏览快手Cookie文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择快手Cookie文件", "", "JSON文件 (*.json);;文本文件 (*.txt);;所有文件 (*)"
        )
        if file_path:
            self.kuaishou_cookie_input.setText(file_path)

    def apply_kuaishou_cookie(self):
        """应用快手Cookie"""
        cookie_input = self.kuaishou_cookie_input.text().strip()
        if not cookie_input:
            show_custom_message(self, "警告", "请输入快手Cookie内容或选择Cookie文件!", "warning")
            return

        try:
            # 获取平台选择（快手）
            platform = "kuaishou"

            # 验证Cookie格式并解析
            from cookie_manager import CookieManager
            cookie_manager = CookieManager()

            cookie_content = ""
            if os.path.exists(cookie_input):
                # 如果是文件路径，读取文件
                try:
                    with open(cookie_input, 'r', encoding='utf-8') as f:
                        cookie_content = f.read().strip()
                except UnicodeDecodeError:
                    show_custom_message(self, "错误", "❌ 快手Cookie文件编码错误！\n请确保文件使用UTF-8编码保存", "error")
                    return
                except Exception as e:
                    show_custom_message(self, "错误", f"❌ 读取快手Cookie文件失败！\n{str(e)}", "error")
                    return
            else:
                # 直接使用输入的Cookie字符串
                cookie_content = cookie_input

            if not cookie_content:
                show_custom_message(self, "错误", "❌ 快手Cookie内容为空！", "error")
                return

            # 解析Cookie
            cookies_dict = cookie_manager.parse_cookie_string(cookie_content)
            if not cookies_dict:
                show_custom_message(self, "错误", "❌ 快手Cookie格式无效！\n请检查Cookie格式是否正确", "error")
                return

            # 清空输入框
            self.kuaishou_cookie_input.clear()

            # 获取主窗口并应用Cookie
            main_window = self.get_main_window()
            if main_window and hasattr(main_window, 'downloader_core'):
                # 使用主窗口的下载核心
                main_window.downloader_core.set_custom_cookies(cookies_dict, platform)
                cookie_count = len(cookies_dict)
            else:
                # 直接保存Cookie
                success = cookie_manager.save_kuaishou_cookies(cookies_dict)

                if not success:
                    show_custom_message(self, "错误", "❌ 快手Cookie保存失败！", "error")
                    return

                cookie_count = len(cookies_dict)

            # 显示成功消息
            show_custom_message(self, "成功", f"✅ 快手Cookie应用成功！\n\n📊 解析结果：\n• 成功解析 {cookie_count} 个Cookie项\n• Cookie已自动保存到本地文件\n• 下次启动时会自动加载", "success")

        except Exception as e:
            show_custom_message(self, "错误", f"❌ 应用快手Cookie时发生错误：\n{str(e)}", "error")

    def reset_kuaishou_cookie(self):
        """重置快手Cookie"""
        try:
            # 清空输入框
            self.kuaishou_cookie_input.clear()

            # 尝试清除保存的Cookie文件
            from cookie_manager import CookieManager
            cookie_manager = CookieManager()

            # 获取平台选择（快手）
            platform = "kuaishou"

            # 清除Cookie文件
            success = cookie_manager.save_kuaishou_cookies({})  # 保存空Cookie字典

            # 清除内存中的Cookie
            main_window = self.get_main_window()
            if main_window and hasattr(main_window, 'downloader_core'):
                main_window.downloader_core.set_custom_cookies({}, platform)

            if success:
                show_custom_message(self, "成功", f"✅ 快手Cookie重置成功！\n\n🔄 重置内容：\n• 清空了Cookie输入框\n• 清除了本地保存的Cookie文件\n• 清除了内存中的Cookie缓存\n• 恢复为默认Cookie配置", "success")
            else:
                show_custom_message(self, "警告", "⚠️ Cookie输入框已清空\n但清除本地Cookie文件时出现问题", "warning")

        except Exception as e:
            # 即使出错，也要清空输入框
            self.kuaishou_cookie_input.clear()
            show_custom_message(self, "警告", f"⚠️ Cookie输入框已清空\n但重置过程中出现错误：{str(e)}", "warning")

    def browse_bilibili_cookie_file(self):
        """浏览B站Cookie文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择B站Cookie文件", "", "JSON文件 (*.json);;文本文件 (*.txt);;所有文件 (*)"
        )
        if file_path:
            self.bilibili_cookie_input.setText(file_path)

    def apply_bilibili_cookie(self):
        """应用B站Cookie"""
        cookie_input = self.bilibili_cookie_input.text().strip()
        if not cookie_input:
            show_custom_message(self, "警告", "请输入B站Cookie内容或选择Cookie文件!", "warning")
            return

        try:
            # 获取平台选择（B站）
            platform = "bilibili"

            # 验证Cookie格式并解析
            from cookie_manager import CookieManager
            cookie_manager = CookieManager()

            cookie_content = ""
            if os.path.exists(cookie_input):
                # 如果是文件路径，读取文件
                try:
                    with open(cookie_input, 'r', encoding='utf-8') as f:
                        cookie_content = f.read().strip()
                except UnicodeDecodeError:
                    show_custom_message(self, "错误", "❌ B站Cookie文件编码错误！\n请确保文件使用UTF-8编码保存", "error")
                    return
                except Exception as e:
                    show_custom_message(self, "错误", f"❌ 读取B站Cookie文件失败！\n{str(e)}", "error")
                    return
            else:
                # 直接使用输入的Cookie字符串
                cookie_content = cookie_input

            if not cookie_content:
                show_custom_message(self, "错误", "❌ B站Cookie内容为空！", "error")
                return

            # 解析Cookie
            try:
                cookies_dict = cookie_manager.parse_cookie_string(cookie_content)
                if not cookies_dict:
                    show_custom_message(self, "错误", "❌ B站Cookie格式错误！\n\n📝 支持的格式：\n• key1=value1; key2=value2\n• key1=value1\n  key2=value2\n• JSON格式", "error")
                    return
            except Exception as e:
                show_custom_message(self, "错误", f"❌ B站Cookie解析失败！\n格式可能不正确：{str(e)}\n\n📝 支持的格式：\n• key1=value1; key2=value2\n• key1=value1\n  key2=value2", "error")
                return

            # 获取主窗口并应用Cookie
            main_window = self.get_main_window()
            if main_window and hasattr(main_window, 'downloader_core'):
                # 使用主窗口的下载核心
                main_window.downloader_core.set_custom_cookies(cookies_dict, platform)
                cookie_count = len(cookies_dict)
            else:
                # 直接保存Cookie
                success = cookie_manager.save_bilibili_cookies(cookies_dict)

                if not success:
                    show_custom_message(self, "错误", "❌ B站Cookie保存失败！", "error")
                    return

                cookie_count = len(cookies_dict)

            # 显示成功消息
            show_custom_message(self, "成功", f"✅ B站Cookie应用成功！\n\n📊 解析结果：\n• 成功解析 {cookie_count} 个Cookie项\n• Cookie已自动保存到本地文件\n• 下次启动时会自动加载", "success")

        except FileNotFoundError:
            show_custom_message(self, "错误", "❌ B站Cookie文件不存在！\n请检查文件路径是否正确", "error")
        except Exception as e:
            show_custom_message(self, "错误", f"❌ 应用B站Cookie时发生未知错误：\n{str(e)}", "error")

    def reset_bilibili_cookie(self):
        """重置B站Cookie"""
        try:
            # 清空输入框
            self.bilibili_cookie_input.clear()

            # 尝试清除保存的Cookie文件
            from cookie_manager import CookieManager
            cookie_manager = CookieManager()

            # 获取平台选择（B站）
            platform = "bilibili"

            # 清除Cookie文件
            success = cookie_manager.save_bilibili_cookies({})  # 保存空Cookie字典

            # 清除内存中的Cookie
            main_window = self.get_main_window()
            if main_window and hasattr(main_window, 'downloader_core'):
                main_window.downloader_core.set_custom_cookies({}, platform)

            if success:
                show_custom_message(self, "成功", f"✅ B站Cookie重置成功！\n\n🔄 重置内容：\n• 清空了Cookie输入框\n• 清除了本地保存的Cookie文件\n• 清除了内存中的Cookie缓存\n• 恢复为默认Cookie配置", "success")
            else:
                show_custom_message(self, "警告", "⚠️ Cookie输入框已清空\n但清除本地Cookie文件时出现问题", "warning")

        except Exception as e:
            # 即使出错，也要清空输入框
            self.bilibili_cookie_input.clear()
            show_custom_message(self, "警告", f"⚠️ Cookie输入框已清空\n但重置过程中出现错误：{str(e)}", "warning")

    def apply_weimiquan_cookie(self):
        """应用微密圈Cookie"""
        cookie_content = self.weimiquan_cookie_text.toPlainText().strip()
        if not cookie_content:
            show_custom_message(self, "提示", "Cookie内容为空，将使用默认Cookie！", "info")
        else:
            show_custom_message(self, "成功", "付费区Cookie已应用！", "success")

    def reset_weimiquan_cookie(self):
        """重置微密圈Cookie"""
        self.weimiquan_cookie_text.clear()
        show_custom_message(self, "成功", "付费区Cookie已重置！", "success")

    def test_proxy(self):
        """测试代理连接"""
        import requests

        proxy_host = self.proxy_host_input.text().strip()
        proxy_port = self.proxy_port_input.value()

        if not proxy_host:
            show_custom_message(self, "警告", "请输入代理主机地址!", "warning")
            return

        try:
            proxies = {
                'http': f'http://{proxy_host}:{proxy_port}',
                'https': f'http://{proxy_host}:{proxy_port}'
            }

            # 测试连接到Google
            response = requests.get('https://www.google.com',
                                  proxies=proxies,
                                  timeout=10)

            if response.status_code == 200:
                show_custom_message(self, "成功", "代理连接测试成功!", "success")
            else:
                show_custom_message(self, "警告", f"代理连接异常，状态码: {response.status_code}", "warning")

        except Exception as e:
            show_custom_message(self, "错误", f"代理连接测试失败: {str(e)}", "error")

    def load_weimiquan_cookies(self):
        """加载微密圈Cookie"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择Cookie文件", "", "JSON文件 (*.json);;文本文件 (*.txt);;所有文件 (*)"
        )
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read().strip()
                    self.weimiquan_cookie_text.setPlainText(content)
                show_custom_message(self, "成功", "Cookie加载成功!", "success")
            except Exception as e:
                show_custom_message(self, "错误", f"加载Cookie失败: {str(e)}", "error")

    def save_weimiquan_cookies(self):
        """保存微密圈Cookie"""
        cookie_content = self.weimiquan_cookie_text.toPlainText().strip()
        if not cookie_content:
            show_custom_message(self, "警告", "Cookie内容为空!", "warning")
            return

        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存Cookie文件", "weimiquan_cookies.txt", "文本文件 (*.txt);;JSON文件 (*.json);;所有文件 (*)"
        )
        if file_path:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(cookie_content)
                show_custom_message(self, "成功", "Cookie保存成功!", "success")
            except Exception as e:
                show_custom_message(self, "错误", f"保存Cookie失败: {str(e)}", "error")

    def get_weimiquan_settings(self):
        """获取微密圈设置"""
        return {
            'proxy_host': self.proxy_host_input.text().strip(),
            'proxy_port': self.proxy_port_input.value(),
            'thread_count': 5,  # 固定为5个线程
            'cookies': self.weimiquan_cookie_text.toPlainText().strip()
        }

    def save_settings(self):
        """保存设置"""
        default_path = self.default_path_input.text().strip()
        if default_path:
            APP_CONFIG['default_download_path'] = default_path

        # 保存微密圈设置到配置文件
        weimiquan_settings = self.get_weimiquan_settings()
        try:
            settings_file = os.path.join(os.getcwd(), 'weimiquan_settings.json')
            with open(settings_file, 'w', encoding='utf-8') as f:
                json.dump(weimiquan_settings, f, ensure_ascii=False, indent=2)
        except Exception:
            pass  # 静默处理设置保存失败

        show_custom_message(self, "成功", "设置已保存!", "success")

    def load_weimiquan_settings(self):
        """加载微密圈设置"""
        try:
            settings_file = os.path.join(os.getcwd(), 'weimiquan_settings.json')
            if os.path.exists(settings_file):
                with open(settings_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)

                self.proxy_host_input.setText(settings.get('proxy_host', '127.0.0.1'))
                self.proxy_port_input.setValue(settings.get('proxy_port', 7890))
                # 线程数固定为5，不需要从设置中读取
                self.weimiquan_cookie_text.setPlainText(settings.get('cookies', ''))
        except Exception:
            pass  # 静默处理设置加载失败

    def create_neon_particle_settings(self):
        """创建霓虹粒子特效设置组"""
        neon_particle_group = QGroupBox("✨ 霓虹粒子特效设置")
        neon_particle_group.setStyleSheet("""
            QGroupBox {
                border: 2px solid rgba(255, 0, 255, 0.6);
                border-radius: 12px;
                margin: 10px 0;
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 rgba(255, 0, 255, 0.1),
                    stop:1 rgba(0, 255, 255, 0.05));
                font-weight: bold;
                font-size: 12pt;
                padding-top: 15px;
                color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 8px 16px;
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff00ff, stop:0.5 #00ffff, stop:1 #ff0080);
                color: #ffffff;
                border-radius: 8px;
                font-weight: bold;
                font-size: 11pt;
                text-shadow: 0 0 10px rgba(255, 0, 255, 0.8);
            }
        """)

        neon_particle_layout = QVBoxLayout(neon_particle_group)
        neon_particle_layout.setContentsMargins(20, 20, 20, 20)
        neon_particle_layout.setSpacing(15)

        # 说明文本
        info_label = QLabel("✨ 赛博朋克风格的动态霓虹粒子背景特效")
        info_label.setStyleSheet("color: #6ca6fd; font-size: 12pt; margin-bottom: 10px; font-weight: bold; text-shadow: 0 0 8px rgba(108,166,253,0.6);")
        neon_particle_layout.addWidget(info_label)

        # 粒子密度设置
        density_layout = QHBoxLayout()
        density_label = QLabel("粒子密度:")
        density_label.setStyleSheet("color: #6ca6fd; font-weight: bold; min-width: 80px; font-size: 12pt; text-shadow: 0 0 8px rgba(108,166,253,0.6);")

        self.neon_particle_density_buttons = []
        density_options = [
            ("稀疏粒子", "low"),
            ("标准密度", "medium"),
            ("粒子风暴", "high")
        ]

        for text, value in density_options:
            btn = QPushButton(text)
            btn.setCheckable(True)
            btn.setProperty("density_value", value)
            btn.setStyleSheet(self.get_neon_particle_button_style())
            btn.clicked.connect(self.on_neon_particle_density_changed)
            self.neon_particle_density_buttons.append(btn)
            density_layout.addWidget(btn)

        # 默认选中标准密度
        self.neon_particle_density_buttons[1].setChecked(True)

        density_row = QHBoxLayout()
        density_row.addWidget(density_label)
        density_row.addLayout(density_layout)
        density_row.addStretch()
        neon_particle_layout.addLayout(density_row)

        # 动画速度设置
        speed_layout = QHBoxLayout()
        speed_label = QLabel("动画速度:")
        speed_label.setStyleSheet("color: #6ca6fd; font-weight: bold; min-width: 80px; font-size: 12pt; text-shadow: 0 0 8px rgba(108,166,253,0.6);")

        self.neon_particle_speed_buttons = []
        speed_options = [
            ("慢速流动", "slow"),
            ("正常速度", "normal"),
            ("极速狂飙", "fast")
        ]

        for text, value in speed_options:
            btn = QPushButton(text)
            btn.setCheckable(True)
            btn.setProperty("speed_value", value)
            btn.setStyleSheet(self.get_neon_particle_button_style())
            btn.clicked.connect(self.on_neon_particle_speed_changed)
            self.neon_particle_speed_buttons.append(btn)
            speed_layout.addWidget(btn)

        # 默认选中正常速度
        self.neon_particle_speed_buttons[1].setChecked(True)

        speed_row = QHBoxLayout()
        speed_row.addWidget(speed_label)
        speed_row.addLayout(speed_layout)
        speed_row.addStretch()
        neon_particle_layout.addLayout(speed_row)

        # 特效开关
        effect_layout = QHBoxLayout()
        effect_label = QLabel("特效开关:")
        effect_label.setStyleSheet("color: #6ca6fd; font-weight: bold; min-width: 80px; font-size: 12pt; text-shadow: 0 0 8px rgba(108,166,253,0.6);")

        self.neon_particle_enabled_btn = QPushButton("开启特效")
        self.neon_particle_enabled_btn.setCheckable(True)
        self.neon_particle_enabled_btn.setChecked(True)
        self.neon_particle_enabled_btn.setStyleSheet(self.get_neon_particle_toggle_style())
        self.neon_particle_enabled_btn.clicked.connect(self.on_neon_particle_enabled_changed)

        effect_layout.addWidget(effect_label)
        effect_layout.addWidget(self.neon_particle_enabled_btn)
        effect_layout.addStretch()
        neon_particle_layout.addLayout(effect_layout)

        return neon_particle_group

    def get_neon_particle_button_style(self):
        """获取霓虹粒子特效按钮样式"""
        return """
            QPushButton {
                background: rgba(0, 0, 0, 0.6);
                border: 2px solid rgba(255, 0, 255, 0.5);
                border-radius: 20px;
                color: white;
                padding: 8px 16px;
                font-size: 10pt;
                font-weight: 500;
                min-width: 80px;
            }
            QPushButton:hover {
                background: rgba(255, 0, 255, 0.2);
                border-color: #ff00ff;
                text-shadow: 0 0 10px rgba(255, 0, 255, 0.8);
            }
            QPushButton:checked {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff00ff, stop:0.5 #00ffff, stop:1 #ff0080);
                border-color: #ff00ff;
                font-weight: bold;
                text-shadow: 0 0 15px rgba(255, 0, 255, 1.0);
            }
        """

    def get_neon_particle_toggle_style(self):
        """获取霓虹粒子特效开关按钮样式"""
        return """
            QPushButton {
                background: rgba(0, 0, 0, 0.6);
                border: 2px solid rgba(255, 0, 255, 0.5);
                border-radius: 20px;
                color: white;
                padding: 10px 20px;
                font-size: 11pt;
                font-weight: 500;
                min-width: 100px;
            }
            QPushButton:hover {
                background: rgba(255, 0, 255, 0.2);
                border-color: #ff00ff;
                text-shadow: 0 0 10px rgba(255, 0, 255, 0.8);
            }
            QPushButton:checked {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff00ff, stop:0.5 #00ffff, stop:1 #ff0080);
                border-color: #ff00ff;
                font-weight: bold;
                text-shadow: 0 0 15px rgba(255, 0, 255, 1.0);
            }
        """

    def on_neon_particle_density_changed(self):
        """霓虹粒子密度改变事件"""
        sender = self.sender()
        density_value = sender.property("density_value")

        # 取消其他按钮的选中状态
        for btn in self.neon_particle_density_buttons:
            if btn != sender:
                btn.setChecked(False)

        # 应用设置
        self.apply_neon_particle_settings()
        self.save_neon_particle_settings()

    def on_neon_particle_speed_changed(self):
        """动画速度改变事件"""
        sender = self.sender()
        speed_value = sender.property("speed_value")

        # 取消其他按钮的选中状态
        for btn in self.neon_particle_speed_buttons:
            if btn != sender:
                btn.setChecked(False)

        # 应用设置
        self.apply_neon_particle_settings()
        self.save_neon_particle_settings()

    def on_neon_particle_enabled_changed(self):
        """特效开关改变事件"""
        enabled = self.neon_particle_enabled_btn.isChecked()
        self.neon_particle_enabled_btn.setText("开启特效" if enabled else "关闭特效")

        # 应用设置
        self.apply_neon_particle_settings()
        self.save_neon_particle_settings()

    def apply_neon_particle_settings(self):
        """应用霓虹粒子特效设置"""
        main_window = self.get_main_window()
        if main_window:
            enabled = self.neon_particle_enabled_btn.isChecked()

            # 获取选中的密度
            density = "medium"
            for btn in self.neon_particle_density_buttons:
                if btn.isChecked():
                    density = btn.property("density_value")
                    break

            # 获取选中的速度
            speed = "normal"
            for btn in self.neon_particle_speed_buttons:
                if btn.isChecked():
                    speed = btn.property("speed_value")
                    break

            main_window.set_neon_particle_settings(enabled, density, speed)

    def save_neon_particle_settings(self):
        """保存霓虹粒子特效设置"""
        try:
            enabled = self.neon_particle_enabled_btn.isChecked()

            density = "medium"
            for btn in self.neon_particle_density_buttons:
                if btn.isChecked():
                    density = btn.property("density_value")
                    break

            speed = "normal"
            for btn in self.neon_particle_speed_buttons:
                if btn.isChecked():
                    speed = btn.property("speed_value")
                    break

            settings = {
                'enabled': enabled,
                'density': density,
                'speed': speed
            }

            settings_file = os.path.join(os.getcwd(), 'neon_particle_settings.json')
            with open(settings_file, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
        except Exception:
            pass  # 静默处理设置保存失败

    def load_neon_particle_settings(self):
        """加载霓虹粒子特效设置"""
        try:
            settings_file = os.path.join(os.getcwd(), 'neon_particle_settings.json')
            if os.path.exists(settings_file):
                with open(settings_file, 'r', encoding='utf-8') as f:
                    settings = json.load(f)

                # 设置开关状态
                enabled = settings.get('enabled', True)
                self.neon_particle_enabled_btn.setChecked(enabled)
                self.neon_particle_enabled_btn.setText("开启特效" if enabled else "关闭特效")

                # 设置密度
                density = settings.get('density', 'medium')
                for btn in self.neon_particle_density_buttons:
                    btn.setChecked(btn.property("density_value") == density)

                # 设置速度
                speed = settings.get('speed', 'normal')
                for btn in self.neon_particle_speed_buttons:
                    btn.setChecked(btn.property("speed_value") == speed)

                # 应用设置
                self.apply_neon_particle_settings()
        except Exception:
            pass  # 静默处理设置加载失败

    def update_neon_particle_visibility(self, visible):
        """更新霓虹粒子特效设置的可见性"""
        if hasattr(self, 'neon_particle_group'):
            self.neon_particle_group.setVisible(visible)

    def get_main_window(self):
        """获取主窗口实例"""
        widget = self
        while widget:
            if isinstance(widget, MainWindow):
                return widget
            widget = widget.parent()
        return None

    def change_password(self):
        """更改付费区访问密码"""
        try:
            from password_settings_dialog import PasswordSettingsDialog

            # 获取主窗口
            main_window = self.get_main_window()
            if not main_window:
                show_custom_message(self, "错误", "无法获取主窗口实例！", "error")
                return

            # 显示密码设置对话框
            dialog = PasswordSettingsDialog(main_window)
            dialog.exec_()

        except ImportError:
            show_custom_message(self, "错误", "密码设置功能模块未找到！", "error")
        except Exception as e:
            show_custom_message(self, "错误", f"打开密码设置时出错：\n{str(e)}", "error")


class SidebarComponent(QWidget):
    """侧边栏组件"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent_window = parent
        self.menu_buttons = []  # 存储菜单按钮引用
        self.setup_ui()

    def setup_ui(self):
        """设置侧边栏UI"""
        self.setFixedWidth(280)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 30, 0, 30)
        layout.setSpacing(0)

        # 应用标题区域 - 毛玻璃效果
        app_title_frame = QFrame()
        app_title_frame.setStyleSheet("""
            QFrame {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 255, 255, 0.15),
                    stop:0.3 rgba(255, 255, 255, 0.12),
                    stop:0.7 rgba(255, 255, 255, 0.08),
                    stop:1 rgba(255, 255, 255, 0.10));
                border: 1px solid rgba(255, 255, 255, 0.2);
                border-radius: 15px;
                margin: 10px;
                backdrop-filter: blur(10px);
            }
        """)
        app_title_layout = QVBoxLayout(app_title_frame)
        app_title_layout.setContentsMargins(10, 15, 10, 15)
        app_title_layout.setSpacing(8)

        # 图标和标题的水平布局
        title_h_layout = QHBoxLayout()
        title_h_layout.setSpacing(8)

        # 应用图标
        icon_label = QLabel("🎬")
        icon_label.setFont(QFont("Segoe UI Emoji", 20))
        icon_label.setStyleSheet("color: #ffffff;")
        icon_label.setAlignment(Qt.AlignCenter)
        icon_label.setFixedSize(40, 40)

        # 应用标题
        app_title_label = QLabel("代飞哥")
        app_title_label.setFont(QFont("Microsoft YaHei UI", 12, QFont.Bold))
        app_title_label.setStyleSheet("""
            color: #ffffff;
            font-weight: 700;
            background: transparent;
            border: none;
        """)
        app_title_label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

        title_h_layout.addWidget(icon_label)
        title_h_layout.addWidget(app_title_label)
        title_h_layout.addStretch()

        # 版本信息
        version_label = QLabel("         1213423722")
        version_label.setFont(QFont("Microsoft YaHei UI", 9, QFont.Medium))
        version_label.setStyleSheet("""
        
            color: rgba(255, 255, 255, 0.8);
            font-weight: 500;
            margin-top: 5px;
            background: transparent;
            border: none;
        """)
        version_label.setAlignment(Qt.AlignLeft)

        app_title_layout.addLayout(title_h_layout)
        app_title_layout.addWidget(version_label)

        layout.addWidget(app_title_frame)
        layout.addSpacing(30)

        # 菜单按钮样式
        menu_button_style = """
            QPushButton {
                background-color: transparent;
                color: #6ca6fd;
                border: none;
                text-align: left;
                padding: 18px 20px 18px 25px;
                font-size: 12pt;
                font-weight: 500;
                border-radius: 12px;
                margin: 3px 15px;
                font-family: 'Microsoft YaHei UI', sans-serif;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 255, 255, 0.1), stop:1 rgba(255, 255, 255, 0.05));
                color: #6ca6fd;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(255, 255, 255, 0.2), stop:1 rgba(255, 255, 255, 0.1));
            }
        """

        # 创建菜单按钮
        douyin_video_btn = QPushButton("🎬 抖音下载区")
        douyin_video_btn.setStyleSheet(menu_button_style)
        douyin_video_btn.clicked.connect(lambda: self.parent_window.switch_page(0))

        kuaishou_video_btn = QPushButton("⚡ 快手下载区")
        kuaishou_video_btn.setStyleSheet(menu_button_style)
        kuaishou_video_btn.clicked.connect(lambda: self.parent_window.switch_page(1))

        bilibili_video_btn = QPushButton("📺 B站下载区")
        bilibili_video_btn.setStyleSheet(menu_button_style)
        bilibili_video_btn.clicked.connect(lambda: self.parent_window.switch_page(2))

        weimiquan_btn = QPushButton("🌸 付费下载区")
        weimiquan_btn.setStyleSheet(menu_button_style)
        weimiquan_btn.clicked.connect(lambda: self.parent_window.switch_page(3))

        settings_btn = QPushButton("⚙️ 设置")
        settings_btn.setStyleSheet(menu_button_style)
        settings_btn.clicked.connect(lambda: self.parent_window.switch_page(4))

        # 保存按钮引用
        self.menu_buttons = [douyin_video_btn, kuaishou_video_btn, bilibili_video_btn, weimiquan_btn, settings_btn]

        # 添加按钮到布局
        for button in self.menu_buttons:
            layout.addWidget(button)

        # 设置第一个按钮为激活状态
        self.set_active_button(0)

        # 添加间距
        layout.addSpacing(30)

        # 底部信息区域
        layout.addStretch()

        # 状态信息
        status_frame = QFrame()
        status_frame.setStyleSheet("""
            QFrame {
                background: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                margin: 10px 10px 10px 15px;
                padding: 10px;
                border: none;
                min-height: 30px;
            }
        """)
        status_layout = QVBoxLayout(status_frame)
        status_layout.setContentsMargins(20, 10, 30, 10)
     

        info_label = QLabel("🚀 高速下载")
        info_label.setFont(QFont("Microsoft YaHei UI", 9, QFont.Medium))
        info_label.setStyleSheet("""
            color: rgba(255, 255, 255, 0.9);
            font-weight: 500;
        """)

        copyright_label = QLabel("© 2025 中鄂智创")
        copyright_label.setFont(QFont("Microsoft YaHei UI", 8))
        copyright_label.setStyleSheet("""
            color: rgba(255, 255, 255, 0.6);
            margin-top: 5px;
        """)

        status_layout.addWidget(info_label)
        status_layout.addWidget(copyright_label)
        layout.addWidget(status_frame)

        # 主题切换按钮
        layout.addSpacing(10)
        self.theme_toggle_btn = QPushButton("🌙 切换到夜间模式")
        self.theme_toggle_btn.setStyleSheet("""
            QPushButton {
                background: rgba(255, 255, 255, 0.1);
                color: rgba(255, 255, 255, 0.9);
                border: 2px solid rgba(255, 255, 255, 0.2);
                border-radius: 8px;
                padding: 10px 15px;
                font-size: 10pt;
                font-weight: 500;
                margin: 5px 15px;
            }
            QPushButton:hover {
                background: rgba(255, 255, 255, 0.2);
                border: 2px solid rgba(255, 255, 255, 0.4);
            }
            QPushButton:pressed {
                background: rgba(255, 255, 255, 0.3);
            }
        """)
        self.theme_toggle_btn.clicked.connect(self.parent_window.toggle_theme)
        layout.addWidget(self.theme_toggle_btn)

    def update_theme(self, is_dark_mode):
        """更新侧边栏主题"""
        if is_dark_mode:
            # 夜间模式
            sidebar_bg = """
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #0c0c0c, stop:0.2 #1a1a2e,
                    stop:0.4 #16213e, stop:0.6 #0f3460,
                    stop:0.8 #533483, stop:1 #2d1b69);
                color: #ffffff;
                border-right: 4px solid qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #00d4ff, stop:0.3 #667eea, stop:0.6 #764ba2, stop:1 #533483);
            """
        else:
            # 日间模式 - 纯蓝色主题（调暗）
            sidebar_bg = """
                background: #003366;
                color: white;
                border-right: 4px solid #004488;
            """

        self.setStyleSheet(f"QWidget {{ {sidebar_bg} }}")

    def set_active_button(self, index):
        """设置激活按钮"""
        from ui_styles import UIStyles
        ui_styles = UIStyles()

        for i, btn in enumerate(self.menu_buttons):
            if i == index:
                btn.setStyleSheet(ui_styles.get_active_menu_button_style())
            else:
                btn.setStyleSheet(ui_styles.get_menu_button_style())



# 全局辅助函数，用于显示自定义消息框
def show_custom_message(parent, title, message, msg_type="info"):
    """显示自定义毛玻璃消息框的全局函数"""
    msg_box = CustomMessageBox(parent, title, message, msg_type)
    return msg_box.exec_()


class CustomMessageBox(QDialog):
    """自定义毛玻璃消息框"""

    def __init__(self, parent=None, title="提示", message="", msg_type="info"):
        super().__init__(parent)
        self.setWindowTitle(title)
        self.setFixedSize(480, 320)  # 增加宽度和高度以适应更多内容
        self.setModal(True)
        self.setWindowFlags(Qt.Dialog | Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

        self.msg_type = msg_type

        # 根据消息类型设置不同的图标
        if msg_type == "success":
            self.icon = "🎉"
        elif msg_type == "error":
            self.icon = "❌"
        elif msg_type == "warning":
            self.icon = "⚠️"
        else:  # info
            self.icon = "ℹ️"

        self.setup_ui(message)

        # 应用毛玻璃效果
        self.apply_glassmorphism_effect()

    def apply_glassmorphism_effect(self):
        """应用毛玻璃效果"""
        # 创建一个容器widget来承载内容，避免主窗口样式影响
        container = QWidget(self)
        container.setGeometry(0, 0, self.width(), self.height())

        # 设置容器的毛玻璃样式 - 粉色主题
        container.setStyleSheet("""
            QWidget {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(255, 182, 193, 0.4),
                    stop:0.3 rgba(255, 192, 203, 0.35),
                    stop:0.7 rgba(255, 160, 180, 0.32),
                    stop:1 rgba(255, 175, 190, 0.38));
                border: 2px solid rgba(255, 182, 193, 0.5);
                border-radius: 25px;
            }
        """)

        # 将主布局设置到容器上
        if hasattr(self, 'main_layout'):
            container.setLayout(self.main_layout)

    def get_button_style(self):
        """获取确定按钮样式 - 与密码验证框相同"""
        return """
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(0, 201, 255, 0.8), stop:1 rgba(146, 254, 157, 0.8));
                color: #ffffff;
                border: 2px solid rgba(0, 201, 255, 0.4);
                border-radius: 15px;
                font-size: 14px;
                font-weight: 600;
                font-family: 'Microsoft YaHei UI', sans-serif;
                padding: 12px 24px;
                min-width: 100px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(0, 201, 255, 0.9), stop:1 rgba(146, 254, 157, 0.9));
                border: 2px solid rgba(0, 201, 255, 0.6);
                box-shadow: 0 0 20px rgba(0, 201, 255, 0.3);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 rgba(0, 201, 255, 0.7), stop:1 rgba(146, 254, 157, 0.7));
                border: 2px solid rgba(0, 201, 255, 0.3);
            }
        """

    def setup_ui(self, message):
        """设置UI界面"""
        # 主布局
        self.main_layout = QVBoxLayout()
        self.main_layout.setContentsMargins(40, 30, 40, 30)
        self.main_layout.setSpacing(25)

        # 添加顶部间距
        self.main_layout.addSpacing(20)

        # 使用传入的实际消息内容
        message_label = QLabel(message)
        message_label.setAlignment(Qt.AlignCenter)
        message_label.setWordWrap(True)  # 启用自动换行
        message_label.setStyleSheet("""
            QLabel {
                color: rgba(255, 255, 255, 0.95);
                font-size: 14px;
                font-weight: 600;
                font-family: 'Microsoft YaHei UI', sans-serif;
                background: transparent;
                border: none;
                padding: 15px;
                line-height: 1.4;
            }
        """)
        self.main_layout.addWidget(message_label)

        # 添加间距
        self.main_layout.addSpacing(20)

        # 确定按钮 - 居中显示
        button_layout = QHBoxLayout()
        button_layout.addStretch()

        self.ok_button = QPushButton("确定")
        self.ok_button.setStyleSheet(self.get_button_style())
        self.ok_button.clicked.connect(self.accept)

        button_layout.addWidget(self.ok_button)
        button_layout.addStretch()

        self.main_layout.addLayout(button_layout)

        # 添加底部间距
        self.main_layout.addSpacing(10)

        # 设置焦点和回车键
        self.ok_button.setFocus()
        self.ok_button.setDefault(True)


class MainWindow(QMainWindow):
    """主窗口类"""

    def __init__(self):
        super().__init__()

        # 设置窗口属性 - 移除系统标题栏
        self.setWindowTitle(APP_CONFIG['window_title'])
        self.setMinimumSize(*APP_CONFIG['window_size'])
        self.resize(*APP_CONFIG['window_size'])
        self.setWindowFlags(Qt.FramelessWindowHint)  # 移除系统标题栏

        self.ui_styles = UIStyles()
        self.is_dark_mode = False
        self.drag_position = None

        # 付费区访问控制
        self.premium_access_granted = False
        self.password_error_count = 0  # 密码错误次数计数器
        self.max_password_attempts = 3  # 最大尝试次数
        self._initialize_premium_password()

        # 初始化下载核心
        from downloader_core import DownloaderCore
        self.downloader_core = DownloaderCore()

        # 初始化霓虹粒子特效
        self.neon_particle_effect = None

        # 确保下载目录存在
        self.ensure_download_directories()

        self.setup_ui()
        self.setup_dynamic_background()
        self.setup_neon_particle_effect()

    def ensure_download_directories(self):
        """确保所有下载目录存在"""
        try:
            for _, path_value in APP_CONFIG['download_paths'].items():
                if not os.path.exists(path_value):
                    os.makedirs(path_value, exist_ok=True)
        except Exception:
            pass  # 静默处理目录创建失败

    def _initialize_premium_password(self):
        """初始化付费区密码"""
        try:
            # 尝试从安全存储或环境变量获取密码
            stored_password = get_password("premium_access", "PREMIUM_PASSWORD")

            if not stored_password:
                # 如果没有存储的密码，使用默认密码并提示用户更改
                default_password = "520184"  # 临时默认密码

                # 存储默认密码（首次运行）
                if store_password("premium_access", default_password):
                    self.premium_password = default_password
                else:
                    self.premium_password = default_password
            else:
                self.premium_password = stored_password

        except Exception:
            # 回退到硬编码密码（临时措施）
            self.premium_password = "520184"
        
        # 确保存储的密码与内存中的密码一致
        try:
            current_stored = get_password("premium_access")
            if current_stored and current_stored != self.premium_password:
                # 使用内存中的密码更新存储
                store_password("premium_access", self.premium_password)
        except Exception:
            pass  # 静默处理密码同步失败

    def _verify_password(self, entered_password: str) -> bool:
        """验证输入的密码

        Args:
            entered_password: 用户输入的密码

        Returns:
            密码是否正确
        """
        try:
            # 每次都从存储中获取最新密码，确保密码修改后立即生效
            current_password = get_password("premium_access", "PREMIUM_PASSWORD")

            if current_password:
                result = entered_password == current_password
                # 更新内存中的密码，保持同步
                self.premium_password = current_password
                return result
            else:
                # 如果没有存储密码，使用实例变量
                result = entered_password == self.premium_password
                return result

        except Exception:
            # 回退到实例变量验证
            result = entered_password == self.premium_password
            return result

    def change_premium_password(self, old_password: str, new_password: str) -> bool:
        """更改付费区密码

        Args:
            old_password: 旧密码
            new_password: 新密码

        Returns:
            是否更改成功
        """
        try:
            # 验证旧密码
            if not self._verify_password(old_password):
                return False

            # 存储新密码
            if store_password("premium_access", new_password):
                # 立即更新内存中的密码
                self.premium_password = new_password
                return True
            else:
                return False

        except Exception:
            return False

    def setup_ui(self):
        """设置UI"""
        # 设置窗口图标
        if os.path.exists("icon.ico"):
            self.setWindowIcon(QIcon("icon.ico"))

        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局 - 垂直布局以容纳标题栏和内容区
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 创建自定义标题栏
        self.custom_titlebar = CustomTitleBar(self)
        main_layout.addWidget(self.custom_titlebar)

        # 创建内容区域
        content_widget = QWidget()
        content_layout = QHBoxLayout(content_widget)
        content_layout.setContentsMargins(0, 0, 0, 0)
        content_layout.setSpacing(0)

        # 创建侧边栏
        self.sidebar = SidebarComponent(self)
        content_layout.addWidget(self.sidebar)

        # 创建页面堆栈
        self.stacked_widget = QStackedWidget()
        # 监听页面切换事件
        self.stacked_widget.currentChanged.connect(self.on_page_changed)
        content_layout.addWidget(self.stacked_widget)

        # 添加内容区域到主布局
        main_layout.addWidget(content_widget)

        # 初始化页面
        self.init_pages()

        # 应用初始主题
        self.apply_theme_styles()

        # 启动动态背景效果
        self.setup_dynamic_background()

        # 启动霓虹粒子特效
        self.setup_neon_particle_effect()

    def init_pages(self):
        """初始化页面"""
        # 抖音视频下载页面 - 索引0
        self.douyin_video_page = DouyinVideoPage(self)
        self.stacked_widget.addWidget(self.douyin_video_page)

        # 抖音图片下载页面 - 索引1（保留但不在菜单中显示）
        self.douyin_image_page = DouyinImagePage(self)
        self.stacked_widget.addWidget(self.douyin_image_page)

        # 快手视频下载页面 - 索引2（菜单中显示为索引1）
        self.kuaishou_video_page = KuaishouVideoPage(self)
        self.stacked_widget.addWidget(self.kuaishou_video_page)

        # B站视频下载页面 - 索引3（菜单中显示为索引2）
        self.bilibili_video_page = BilibiliVideoPage(self)
        self.stacked_widget.addWidget(self.bilibili_video_page)

        # 微密圈下载页面 - 索引4（菜单中显示为索引3）
        self.weimiquan_page = WeimiquanPage(self)
        self.stacked_widget.addWidget(self.weimiquan_page)

        # 设置页面 - 索引5（菜单中显示为索引4）
        self.settings_page = SettingsPage(self)
        self.stacked_widget.addWidget(self.settings_page)

        # 默认显示第一个页面
        self.stacked_widget.setCurrentIndex(0)

    def switch_page(self, index):
        """切换页面"""
        # 侧边栏菜单索引映射到实际页面索引
        # 菜单索引0: 抖音视频下载 -> 实际索引0
        # 菜单索引1: 快手视频下载 -> 实际索引2
        # 菜单索引2: B站视频下载 -> 实际索引3
        # 菜单索引3: 付费下载区 -> 实际索引4
        # 菜单索引4: 设置 -> 实际索引5

        page_mapping = {
            0: 0,  # 抖音视频下载
            1: 2,  # 快手视频下载
            2: 3,  # B站视频下载
            3: 4,  # 付费下载区
            4: 5   # 设置
        }

        # 获取实际页面索引
        actual_index = page_mapping.get(index, index)

        if 0 <= actual_index < self.stacked_widget.count():
            # 如果是付费下载区（实际索引4），需要验证密码
            if actual_index == 4 and not self.premium_access_granted:
                if self.verify_premium_access():
                    self.premium_access_granted = True
                    self.stacked_widget.setCurrentIndex(actual_index)
                    # 更新侧边栏按钮选中状态
                    self.sidebar.set_active_button(index)
                # 如果密码验证失败，不切换页面
            else:
                self.stacked_widget.setCurrentIndex(actual_index)
                # 更新侧边栏按钮选中状态
                self.sidebar.set_active_button(index)

    def verify_premium_access(self):
        """验证付费区访问密码"""
        # 检查是否已达到最大尝试次数
        if self.password_error_count >= self.max_password_attempts:
            final_error_dialog = CustomMessageBox(
                self,
                "安全警告",
                f"❌ 密码错误次数过多！\n\n为了安全起见，程序将自动退出。\n已尝试 {self.password_error_count} 次，超过最大限制 {self.max_password_attempts} 次。",
                "error"
            )
            final_error_dialog.exec_()

            # 退出程序
            import sys
            sys.exit(1)

        # 使用毛玻璃风格密码对话框
        from glassmorphism_dialog import GlassmorphismPasswordDialog
        dialog = GlassmorphismPasswordDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            entered_password = dialog.get_password()
            if self._verify_password(entered_password):
                # 密码正确，重置错误计数器
                self.password_error_count = 0
                success_dialog = CustomMessageBox(
                    self,
                    "验证成功",
                    "🎉 欢迎访问付费下载区！\n\n您现在可以使用所有高级功能",
                    "success"
                )
                success_dialog.exec_()
                return True
            else:
                # 密码错误，增加错误计数器
                self.password_error_count += 1
                remaining_attempts = self.max_password_attempts - self.password_error_count

                if remaining_attempts > 0:
                    error_dialog = CustomMessageBox(
                        self,
                        "验证失败",
                        f"❌ 密码错误，请重试！\n\n请确认您输入的密码是否正确\n剩余尝试次数：{remaining_attempts} 次",
                        "error"
                    )
                    error_dialog.exec_()
                else:
                    # 已达到最大尝试次数，显示警告并退出
                    final_error_dialog = CustomMessageBox(
                        self,
                        "安全警告",
                        f"❌ 密码错误次数过多！\n\n为了安全起见，程序将自动退出。\n已尝试 {self.password_error_count} 次，达到最大限制。",
                        "error"
                    )
                    final_error_dialog.exec_()

                    # 退出程序
                    import sys
                    sys.exit(1)

                return False
        return False

    def toggle_theme(self):
        """切换主题"""
        self.is_dark_mode = not self.is_dark_mode

        # 停止所有动态背景效果，保持固定样式
        if hasattr(self, 'bg_timer') and self.bg_timer.isActive():
            self.bg_timer.stop()

        self.apply_theme_styles()

        # 更新自定义标题栏主题
        if hasattr(self, 'custom_titlebar'):
            self.custom_titlebar.update_theme(self.is_dark_mode)

        # 更新侧边栏主题
        self.sidebar.update_theme(self.is_dark_mode)

        # 更新主题切换按钮文字
        if self.is_dark_mode:
            self.sidebar.theme_toggle_btn.setText("☀️ 切换日夜")
        else:
            self.sidebar.theme_toggle_btn.setText("🌙 切换日夜")

        # 更新霓虹粒子特效
        self.update_neon_particle_effect()

        # 更新设置页面中霓虹粒子特效设置的可见性
        if hasattr(self, 'settings_page'):
            self.settings_page.update_neon_particle_visibility(not self.is_dark_mode)  # 只在日间模式显示

    def apply_theme_styles(self):
        """应用主题样式"""
        # 所有模式都使用静态背景，不再动态切换
        bg_state = 0  # 固定使用静态背景
        main_style = self.ui_styles.get_main_style(self.is_dark_mode, bg_state)
        self.setStyleSheet(main_style)

        # 应用圆角遮罩
        self.apply_rounded_corners()

    def apply_rounded_corners(self):
        """应用圆角遮罩"""
        # 创建圆角遮罩
        radius = 15
        size = self.size()

        # 创建位图
        bitmap = QBitmap(size)
        bitmap.fill(Qt.color0)  # 填充为透明

        # 在位图上绘制圆角矩形
        painter = QPainter(bitmap)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.color1)  # 填充为不透明
        painter.setPen(Qt.NoPen)

        # 绘制圆角矩形
        rect = bitmap.rect()
        painter.drawRoundedRect(rect, radius, radius)
        painter.end()

        # 应用遮罩
        self.setMask(bitmap)



    def update_page_styles(self):
        """更新页面样式"""
        if self.is_dark_mode:
            title_color = "#6ca6fd"
            text_color = "#ffffff"  # 使用白色文字
        else:
            title_color = "#ffffff"  # 日间模式也使用白色标题
            text_color = "#ffffff"  # 日间模式也使用白色文字，在深蓝背景上清晰可见

        # 更新所有页面的标签颜色
        for i in range(self.stacked_widget.count()):
            page = self.stacked_widget.widget(i)
            for label in page.findChildren(QLabel):
                if label.font().pointSize() == 16 and label.font().bold():  # 页面标题
                    label.setStyleSheet(f"color: {title_color} !important; margin-bottom: 10px;")
                elif "使用说明" in label.text():  # 说明文本
                    continue  # 保持原有样式
                else:
                    label.setStyleSheet(f"color: {text_color} !important;")

        # 更新输入框样式
        input_style = self.ui_styles.get_input_style(self.is_dark_mode)
        for i in range(self.stacked_widget.count()):
            page = self.stacked_widget.widget(i)
            for input_field in page.findChildren(QLineEdit):
                input_field.setStyleSheet(input_style)

    def setup_dynamic_background(self):
        """设置动态背景效果 - 已禁用，保持固定样式"""
        # 背景动画状态 - 固定为0，不再变化
        self.bg_animation_state = 0

        # 不再启用动态背景，保持固定样式
        # 注释掉动态背景相关代码
        # if not self.is_dark_mode:
        #     self.bg_timer = QTimer()
        #     self.bg_timer.timeout.connect(self.update_dynamic_background)
        #     self.bg_timer.start(5000)

    def update_dynamic_background(self):
        """更新动态背景"""
        self.bg_animation_state = (self.bg_animation_state + 1) % 4

        # 不直接调用setStyleSheet，而是重新应用完整的主题样式
        self.apply_theme_styles()

    # 鼠标拖拽事件现在由自定义标题栏处理

    def setup_neon_particle_effect(self):
        """设置霓虹粒子特效"""
        if self.neon_particle_effect is None:
            self.neon_particle_effect = NeonParticleEffect(self)
            self.neon_particle_effect.setGeometry(0, 0, self.width(), self.height())
            self.neon_particle_effect.lower()  # 确保在最底层

        # 只在日间模式显示霓虹粒子特效
        if not self.is_dark_mode:
            self.neon_particle_effect.set_enabled(True)
            self.neon_particle_effect.show()
        else:
            self.neon_particle_effect.set_enabled(False)
            self.neon_particle_effect.hide()

    def update_neon_particle_effect(self):
        """更新霓虹粒子特效"""
        if self.neon_particle_effect:
            # 只在日间模式显示霓虹粒子特效
            if not self.is_dark_mode:
                self.neon_particle_effect.set_enabled(True)
                self.neon_particle_effect.show()
                self.neon_particle_effect.lower()  # 确保在最底层
            else:
                self.neon_particle_effect.set_enabled(False)
                self.neon_particle_effect.hide()

    def set_neon_particle_settings(self, enabled, density, speed):
        """设置霓虹粒子特效参数"""
        if self.neon_particle_effect:
            self.neon_particle_effect.set_enabled(enabled)
            self.neon_particle_effect.set_particle_density(density)
            self.neon_particle_effect.set_animation_speed(speed)

    def resizeEvent(self, event):
        """窗口大小改变事件"""
        super().resizeEvent(event)

        # 更新霓虹粒子特效大小
        if self.neon_particle_effect:
            self.neon_particle_effect.setGeometry(0, 0, self.width(), self.height())

        # 延迟应用圆角，确保窗口大小已经更新
        QTimer.singleShot(10, self.apply_rounded_corners)

        # 更新页面中的动态样式
        self.update_page_styles()

    def on_page_changed(self, index):
        """页面切换时的处理"""
        try:
            current_widget = self.stacked_widget.widget(index)
            if current_widget:
                # 如果是抖音视频下载页面（索引0）
                if index == 0 and hasattr(current_widget, 'update_button_styles'):
                    current_widget.update_button_styles(True)  # 视频按钮激活
                # 如果是抖音图片下载页面（索引1）
                elif index == 1 and hasattr(current_widget, 'update_button_styles'):
                    current_widget.update_button_styles(False)  # 图片按钮激活

            # 更新侧边栏按钮选中状态
            # 实际页面索引到菜单索引的反向映射
            reverse_mapping = {
                0: 0,  # 抖音视频下载 -> 菜单索引0
                2: 1,  # 快手视频下载 -> 菜单索引1
                3: 2,  # B站视频下载 -> 菜单索引2
                4: 3,  # 付费下载区 -> 菜单索引3
                5: 4   # 设置 -> 菜单索引4
            }
            menu_index = reverse_mapping.get(index, -1)
            if menu_index >= 0:
                self.sidebar.set_active_button(menu_index)

        except Exception:
            pass  # 静默处理页面切换错误
